aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/models/owner.rb
blob: ebaafdec5edaf9e605d91daddcb0303717154b19 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true

class Owner < ActiveRecord::Base
  self.primary_key = :owner_id
  has_many :pets, -> { order Arel.sql("pets.name desc") }
  has_many :toys, through: :pets
  has_many :persons, through: :pets

  belongs_to :last_pet, class_name: "Pet"
  scope :including_last_pet, -> {
    select('
      owners.*, (
        select p.pet_id from pets p
        where p.owner_id = owners.owner_id
        order by p.name desc
        limit 1
      ) as last_pet_id
    ').includes(:last_pet)
  }

  after_commit :execute_blocks

  accepts_nested_attributes_for :pets, allow_destroy: true

  def blocks
    @blocks ||= []
  end

  def on_after_commit(&block)
    blocks << block
  end

  def execute_blocks
    blocks.each do |block|
      block.call(self)
    end
    @blocks = []
  end
end