Sto cercando un chiaro esempio di Rails 4 su come filtrare i record in base ai dati ad essi associati tramite un'altra tabella.Query Rails: Filtra per proprietà in un'altra tabella
Supponiamo di avere un modello Utenti e un modello Commenti. Un utente has_many
commenti e un commento belongs_to
un utente. Un commento ha anche una colonna score
nella sua tabella.
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 |
| ... |
Come potrei ottenere tutti gli utenti che hanno fatto un commento con il contenuto "k" che ha un punteggio> 0? Nota che quello che voglio restituire sono gli utenti, non i commenti.
Inoltre, si consideri un esempio più complesso, in cui un utente has_many
commenti e gli piace, commenti belong_to
un utente, ed un commento has_many
piace. Mi piace belong_to
un utente e belong_to
un commento. Si noti che score
non è più un fattore in questo esempio.
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 |
| ... |
In questo secondo esempio, come faccio a trovare tutti gli utenti che hanno mai avuto uno di loro commenti gradito da parte dell'utente chiamato 'Fonzie'?