scopes

ruby
class Document < ApplicationRecord
  belongs_to :owner, class_name: "User"
  has_many :visibilities, class_name: "DocumentVisibility", dependent: :delete_all

  scope :public_documents, -> { where(is_public: true) }

Polymorphic “Visible To” Scope with Arel

rails activerecord arel
by codesnips 3 tabs
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

Laravel scopes for reusable query logic

laravel eloquent scopes
by Carlos Mendez 2 tabs
ruby
module ExistenceChecks
  extend ActiveSupport::Concern

  class_methods do
    def has_any?(conditions = {})
      relation = conditions.present? ? where(conditions) : all

Fast “Exists” Checks with select(1) and LIMIT

rails activerecord performance
by codesnips 4 tabs
php
<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

Laravel global query scopes with database views

laravel scopes database-views
by Carlos Mendez 4 tabs
ruby
class User < ApplicationRecord
  has_many :posts
  has_many :comments

  scope :digest_subscribers, -> {
    where(digest_opt_in: true).where.not(confirmed_at: nil)

Weekly Digest Emails in Rails with a Cron Job and Query Scopes

rails activejob sidekiq-cron
by codesnips 4 tabs
ruby
class Cart < ApplicationRecord
  has_many :cart_items, dependent: :destroy

  EXPIRY_WINDOW = 2.hours

  scope :active, -> { where(state: :active) }

Expire Stale Shopping Carts With a Rails Scope and a Recurring Reaper Job

rails activerecord background-jobs
by codesnips 3 tabs
ruby
class OverdueInvoicesQuery
  def initialize(relation: Invoice.all, as_of: Time.current)
    @relation = relation
    @as_of = as_of
  end

ActiveRecord::Relation as a Boundary (No Arrays)

rails activerecord query-objects
by codesnips 3 tabs
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Soft-Delete and Restore Blog Posts with a Trash View in Laravel

laravel eloquent soft-deletes
by codesnips 4 tabs
ruby
class Article < ApplicationRecord
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings

  scope :published, -> { where.not(published_at: nil) }

Filtering a Listing by Tags with a has_many :through Scope and a Query Object

rails activerecord has-many-through
by codesnips 3 tabs