【问题标题】:Turning a Rails AssociationRelation into a CollectionProxy将 Rails AssociationRelation 转换为 CollectionProxy
【发布时间】: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 &lt;&lt; a_lion_or_a_tiger

我要做的是直接为动物园启用lionstigers方法。

我可以轻松地进行检索:

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.lionsa_zoo.tigers

【问题讨论】:

    标签: ruby-on-rails rails-models


    【解决方案1】:

    你在找has_many :lions, through :animals,看看http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

    此外,鉴于 Animal 可以是不同的类型,您应该检查多态关联。

    【讨论】:

    • 这是一个解决方案吗?我知道has_many :through,但我没有使用它,因为我认为它不能应用于泛化
    • 我不确定你所说的概括是什么意思,但这就是我处理类似情况的方式。
    • 泛化实际上是一个超类。 AnimalLion 的泛化,它是Animal 本身的特化。当与父模型的关联已经存在时,我不确定添加 has_many :through 关联是否可行。
    猜你喜欢
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多