Rails, how to find without related records

I know that it will be easy, but I am having real problems.

I have users that can have many results. I am trying to figure out how to return users who do not yet have results for the @starter object (from the controller).

@users = @event.entires @starters = @users.where("results = ?", 0) 

can someone explain how can I check if the user has any results?

+6
source share
4 answers

The best decision (as Mr. Yoshiji commented)

 @starters = @users.includes(:results).where(results: { id: nil }) 

This will fulfill the same request as in my second solution.

Another SQL solution

You can use LEFT OUTER JOIN . Thus, you will always have all the results from the "left" table ( users ), but you will also have the corresponding entries for the "right" ( results ) table, although not, which will leave you with empty fields that you can check.

 @starters = @users.joins("LEFT OUTER JOIN results ON results.user_id = users.id").where("results.user_id IS NULL") 

In your case, replace users with the name of your "custom" model.

Another Ruby Solution

 @starters = @users.select { |u| !!u.results } 

Here !! will result in conversion to a boolean, if there are no results , u.results will return [] (empty array). And !![] is true .

+12
source

Try to get up and find which one is null

 @users.joins("LEFT OUTER JOIN user ON user.id = result.user_id").where("result.id IS NULL") 
0
source

If your @users is an array, try:

 @starters = @users.select { |u| u.results.empty? } 
0
source

This should get all users who have no results:

 @starters = ActiveRecord::Base.execute("select * from users where id not in (select user_id from results)") 

Another way to do this would be as follows:

 User.where("id not in ?", "(select user_id from results)") 
0
source

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


All Articles