如何定义嵌套的has_one关联?

时间:2016-04-04 12:40:44

标签: ruby-on-rails associations

假设我们有这种人为的模型结构

class Apple < ActiveRecord::Base
  belongs_to :fruit
  has_one :tree, through: :fruit
  has_one :organism, through: :tree
end

class Fruit < ActiveRecord::Base
  belongs_to :tree
  has_many :apples      
end

class Tree < ActiveRecord::Base
  belongs_to :organism
  has_many :fruits
end

class Organism < ActiveRecord::Base
  has_many :trees
end

为了避免必须调用@apple.fruit.tree.organism,我已经在Apple中定义了两个has_one-through指令,并期望@apple.organism能够正常工作,但事实并非如此。 @apple.tree.organism确实有用。

我做错了吗?我是否应该为Apple实例上的有机体定义一个getter方法并完成它?

1 个答案:

答案 0 :(得分:0)

您的has_one在技术上具有belongs_to的特征:认为有机体has_many苹果through树而不是相反。 “belongs_to:through”在Rails中不起作用,因此我建议在模型中使用delegate

class Apple < ActiveRecord::Base
  delegate :organism, to: :fruit
end

class Fruit < ActiveRecord::Base
  delegate :organism, to :tree      
end