0

我正在尝试在 Rails 中学习 arel/scopes.. 我有以下模型..

Class Category
  has_many :questions

Class Question
  belongs_to :category
  has_many :answers

Class Answer
  belongs_to :question
  # attributes: owner_name

我正在尝试查找与 owner_name 有答案的类别,例如“bob”。为此,我正在考虑添加一个 has_many :through 类别和答案之间的关系,然后使用..访问类别的答案

Category.find_each do |c|
  c.answers.find_by_owner_name("bob")
end

..但这似乎有点矫枉过正,而且很冗长。我可以使用 Category 类中定义的范围更好地做到这一点吗?

谢谢。

4

2 回答 2

0
@categories = Answer.where(:owner_name => "Bob").collect(&:category)

您可以使用委托来实现这一点:

Class Answer
  belongs_to :question
  delegate :category, :to => :question, :allow_nil => true
end

或者,如果您不想使用该delegate方法,则可以这样做:

@categories = Answer.where(:owner_name => "Bob").collect(&:question).collect(&:category)
于 2013-04-11T18:52:40.383 回答
0

find_each 方法肯定会在性能方面扼杀你。您对创建 has_many :through 类别和答案之间的关系是正确的。一旦你有了它,它就是直截了当的:

Category.joins(:answers).where("answers.owner_name = ?", "Bob")
于 2013-04-11T19:36:05.990 回答