Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails how to find with no associated records

I know that this will be an easy one but I'm having real issues working it out.

I have users that can have_many results. I'm trying to work out how to return users that don't yet have any results to the @starters object(from the controller).

@users = @event.entires

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

could anyone explain how i would check if a user has no results?

like image 381
old_no_7uk Avatar asked Oct 03 '13 20:10

old_no_7uk


1 Answers

Best solution (as MrYoshiji commented)

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

This will execute the same query as the one in my second solution.

Other SQL solution

You could use a LEFT OUTER JOIN. This way, you will always have all the results from the "left" table (users) but you will also have matching records for the "right" table (results) eventhough there are non, 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 "user" model.

Other Ruby solution

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

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

like image 127
Raindal Avatar answered Oct 20 '22 00:10

Raindal