我正在尋求清晰的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」用戶喜歡?