Josué Lima
Josué Lima

Reputation: 483

Add conditions do activerecord includes

First I have this:

has_one :guess scope :with_guesses, ->{ includes(:guess) }

Which loads all guesses (if they exists) for a 'X' model (run two queries). That's ok. works perfectly.

But I need to add one more condition to It.

If I do (my first thought):

scope :with_guesses, ->(user) { includes(:guess).where("guesses.user_id = ?", user.id) }

It will also run ok, BUT in one query (join) which will exclude results that doesn't have a 'guess'.

Any tips on how to use include with conditions but KEEPING the results that don't have a 'guess' ?

UPDATE

I ended up solving this by using a decorator, which I can pass the user as a context in the controller call, keeping the views clean.

I've used the Draper gem (https://github.com/drapergem/draper) to do this. You don't really need a gem to work with decorators in rails, but it can be helpful.

Upvotes: 1

Views: 3537

Answers (2)

epsilones
epsilones

Reputation: 11609

I didn't test it but you can use something like

User.eager_load(:guesses).where("guesses.user_id = ?", user.id)

Upvotes: 1

Chuanpin Zhu
Chuanpin Zhu

Reputation: 2256

when you using includes and where, the includes left join will be inner join.

so if you want to using a left join with where, you have to use string sql fragment:

scope :with_guesses, ->(user) { joins('left outer join guesses on guesses.user_id = ?', 

  user.id)} 

I didn't test this code above, you have to test it yourself, this is just a way to think about

this problem.

here is reference:

http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations

Upvotes: 0

Related Questions