如何定义嵌套的has_one关联?

How to define a nested has_one association?

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

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 实例上为 :organism 定义一个 getter 方法并完成它?

你的 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