2015-03-30 29 views
5

我正在尋求清晰的Rails 4示例,瞭解如何基於與其關聯的數據通過另一個表來過濾記錄。Rails查詢:按另一個表中的屬性過濾

假設我有一個用戶模型和一個評論模型。用戶has_many評論以及評論belongs_to用戶。評論的表格中還有一個score列。

class User < ActiveRecord::Base 
    has_many :comments 
end 

Users 
| id | name | email    | 
|-----|---------|---------------------| 
| 1 | "Alice" | "[email protected]" | 
| 2 | "Bob" | "[email protected]" | 
| ...         | 

class Comment < ActiveRecord::Base 
    belongs_to :user 
end  

Comments 
| id | score | content   | user_id | 
|-----|-------|------------------|---------| 
| 1 | 0  | "lol"   | 2  | 
| 2 | 2  | "more like love" | 3  | 
| ...          | 

如何我會獲得已與內容 「K」 具有得分> 0評論所有用戶?請注意,我想返回的是用戶,而不是評論。


另外,考慮更復雜的例子,當用戶has_many意見和喜歡,評論belong_to用戶和評論has_many喜歡。喜歡belong_to a用戶和belong_to評論。請注意,score不再是本示例中的一個因素。

class User < ActiveRecord::Base 
    has_many :comments 
    has_many :likes 
end 

Users 
| id | name | email    | 
|-----|---------|---------------------| 
| 1 | "Alice" | "[email protected]" | 
| 2 | "Bob" | "[email protected]" | 
| ...         | 

class Comment < ActiveRecord::Base 
    belongs_to :user 
    has_many :likes 
end 

Comments 
| id | content   | user_id | 
|-----|------------------|---------| 
| 1 | "lol"   | 2  | 
| 2 | "more like love" | 3  | 
| ...        | 

class Like < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :comment 
end 

Likes 
| id | user_id | comment_id | 
|-----|---------|------------| 
| 1 | 1  | 2   | 
| 2 | 4  | 3   | 
| ...      | 

在第二個例子中,我如何才能找到誰擁有所有用戶曾有他們的意見通過一個名爲「Fonzie」用戶喜歡?

回答

4

回答你的第一個問題。您需要創建一個新的表格結構來引用用戶和評論表之間的關聯。

這可以通過User.joins(:comments)來實現。現在你有一張表格,所有用戶都有相關的評論。要應用您的過濾器,你可以簡單地做:

User.joins(:comments) .where("comments.content = ? AND comments.score > ?", 'some_content', 0)

如果你不熟悉以上情況,我建議你閱讀rails guidelines on queries - 搜索「連接表」

由於第二個例子是有點複雜,我建議你先熟悉上面的指南。

相關問題