【发布时间】:2014-04-23 22:01:13
【问题描述】:
假设我有这些课程:
class Zoo < ActiveRecord::Base
has_many :animals
end
class Animal < ActiveRecord::Base;
belongs_to :zoo
end
class Lion < Animal; end
class Tiger < Animal; end
我可以轻松做到a_zoo.animals,而且a_zoo.animals << a_lion_or_a_tiger。
我要做的是直接为动物园启用lions和tigers方法。
我可以轻松地进行检索:
def lions
animals.where(type: 'Lion')
end
# analogous for the tiger, can be generalized with metaprogramming
# but right now there's no need to
但我很难进行修改。也就是说,a_zoo.lions 返回一个AssociationRelation,而a_zoo.animals 返回一个CollectionProxy,据我所知,这是可更新的。
如何将a_zoo.animals 的所有功能转移到a_zoo.lions 和a_zoo.tigers?
【问题讨论】:
标签: ruby-on-rails rails-models