Say I have these classes:
class Zoo < ActiveRecord::Base
has_many :animals
end
class Animal < ActiveRecord::Base;
belongs_to :zoo
end
class Lion < Animal; end
class Tiger < Animal; end
I can easily do a_zoo.animals
but moreover a_zoo.animals << a_lion_or_a_tiger
.
What I want to do is directly enable the lions
and tigers
method for a zoo.
I can easily do the retrieving:
def lions
animals.where(type: 'Lion')
end
# analogous for the tiger, can be generalized with metaprogramming
# but right now there's no need to
but I'm having a hard time with the modifications. That is, a_zoo.lions
returns an AssociationRelation
while a_zoo.animals
returns a CollectionProxy
, which is updatable as far as I'm getting this.
What can I do to have all the functionality of a_zoo.animals
transferred to a_zoo.lions
and a_zoo.tigers
?