2017-07-09 17:41:28 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2008-01-31 07:50:15 +00:00
|
|
|
class Owner < ActiveRecord::Base
|
2011-11-29 18:58:41 +00:00
|
|
|
self.primary_key = :owner_id
|
2016-08-06 16:26:20 +00:00
|
|
|
has_many :pets, -> { order "pets.name desc" }
|
2016-04-06 03:46:55 +00:00
|
|
|
has_many :toys, through: :pets
|
|
|
|
has_many :persons, through: :pets
|
2013-08-26 17:15:37 +00:00
|
|
|
|
2016-08-06 16:26:20 +00:00
|
|
|
belongs_to :last_pet, class_name: "Pet"
|
2014-06-03 02:07:02 +00:00
|
|
|
scope :including_last_pet, -> {
|
2016-08-06 18:20:22 +00:00
|
|
|
select('
|
2014-06-03 02:07:02 +00:00
|
|
|
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
|
2016-08-06 18:20:22 +00:00
|
|
|
').includes(:last_pet)
|
2014-06-03 02:07:02 +00:00
|
|
|
}
|
|
|
|
|
2013-08-26 17:15:37 +00:00
|
|
|
after_commit :execute_blocks
|
|
|
|
|
2013-03-25 14:58:23 +00:00
|
|
|
accepts_nested_attributes_for :pets, allow_destroy: true
|
|
|
|
|
2013-08-26 17:15:37 +00:00
|
|
|
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
|
2009-03-09 13:42:51 +00:00
|
|
|
end
|