[英]Rails Nested Associations and Scopes
我正在嘗試在Rails中學習球/范圍。我有以下模型。
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類中定義的范圍更好地做到這一點嗎?
謝謝。
@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)
find_each方法肯定會損害您的性能。 在Category和Answer之間創建has_many:through關系是正確的。 一旦有了它,就很簡單了:
Category.joins(:answers).where("answers.owner_name = ?", "Bob")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.