2016-05-25 55 views

回答

3

使用has_many :through關係:

# Category.rb 
has_many :topics 
has_many :answers, through: :topics 

現在你可以從所有主題訪問所有的答案,像這樣:

Category.first.answers.count 
1

如果你在你的模式配置(即不使用has_many :through),你會想開始Answers並利用幾個join s到去Category

Answers.joins(topic: :category).where(categories: { id: category_id }) 

在這裏,我們要加入一個嵌套的關聯,然後使用WHERE子句來過濾出由category_id

注:我認爲這是正確的語法,但您可能需要反覆折騰多個topiccategory

+0

我真的忘記了的has_many:通過,但它始終是偉大的,有很多解決方案1問題。謝謝! – Src