Rails query: filter by properties in another table

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 | |-----|-------|------------------|---------| | 1 | 0 | "lol" | 2 | | 2 | 2 | "more like love" | 3 | | ... | 

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?

+5
source share
1 answer

To answer your first question. You need to create a new table structure that references the association between user and comment tables.

This can be achieved using User.joins(:comments) . Now you have a table in which there are all users with relevant comments. To apply filters, you can simply:

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

If you are not familiar with the foregoing, I suggest you read the recommendations on rails for queries - the search "Join tables"

Since the second example is a bit more complicated, I would advise you to first familiarize yourself with the above guides.

+4
source

Source: https://habr.com/ru/post/1216494/


All Articles