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?
@starters = @users.includes(:results).where(results: { id: nil })
This will execute the same query as the one in my second 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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With