I am looking for a clear Rails 4 example on how to filter records based on the data associated with them through another table.
Suppose I have a user model and a comment model. User comments has_many and user belongs_to comment. A comment also has a score column in its table.
class User < ActiveRecord::Base has_many :comments end
Users | id | name | email | |-----|---------|---------------------| | 1 | "Alice" | " alice@example.com " | | 2 | "Bob" | " bob@example.com " | | ... |
class Comment < ActiveRecord::Base belongs_to :user end Comments | id | score | content | user_id | |
How can I get all the users who made a comment with content "k" that has a rating> 0? Please note that I want to return, these are Users, not Comments.
In addition, consider a more complex example where has_many user comments and reviews, user belong_to comments, and has_many like comment. Likes belong_to User and belong_to comment. Note that score no longer a factor in this example.
class User < ActiveRecord::Base has_many :comments has_many :likes end
Users | id | name | email | |-----|---------|---------------------| | 1 | "Alice" | " alice@example.com " | | 2 | "Bob" | " bob@example.com " | | ... |
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 this second example, how would I find all Users who have ever used one of their comments that a User with the name "Fonzie" liked?