Rails传递模型关联查询

时间:2014-09-09 04:14:35

标签: sql ruby-on-rails ruby

编辑:假设A是"论坛",B是"主题"和C是" Post"。

模型A has_many B(B belongs_to A)

模型B has_many C(C belongs_to B)

问题:如何直接查询模型A has_many C(和C属于A)?

2 个答案:

答案 0 :(得分:4)

让我们说你的" A"是"论坛",你的" B"是"主题"和你的" C"是Post

<强>论坛

has_many :topics
has_many :posts, through: :topics

<强>主题

belongs_to :forum
has_many :posts

发表

belongs_to :topic

def forum
  topic.forum
end

答案 1 :(得分:3)

Ryan Bigg对has_many :through (official documentation)是对的,但我建议委托对方:

class Category < ActiveRecord::Base
  has_many :foods
  has_many :recipes, through: :foods
end

class Food < ActiveRecord::Base
  belongs_to :category
  has_many :recipes
end

class Recipe < ActiveRecord::Base
  belongs_to :food
  delegate :category, to: :food
    allow_nil: true
end

使用Module#delegate比委托方法更方便,并使用Rails提供的语法糖。您还可以设置前缀和内容。阅读demeter定律(Do not break the law of Demeter!)和Module#delegate API documentation