Jay
Jay

Reputation: 237

Eager loading with conditions

The newer style of eager loading uses multiple queries to load associations. Is it possible to add conditions to those additional eager loading queries? e.g.

Bakery.find(:all, :include => :bakers)

will generate an eager loading query similar to this:

SELECT bakers.* FROM bakers WHERE (bakers.bakery_id IN (1,2,3,4,5))

Is it possible to add conditions to this eager loading query?

Update: To (maybe) make this clearer, the query I am wanting to replicate with AR (sans SQL) is:

SELECT * FROM bakeries LEFT JOIN bakers ON bakeries.id=bakers.bakery_id AND bakers.hat = 'on'

Specifically, I was hoping to be able to modify the second eager loaded SQL statement to be:

SELECT bakers.* FROM bakers WHERE (bakers.bakery_id IN (1,2,3,4,5) AND bakers.hat = 'on')

Is this possible, or must I use SQL? Just looking for the "Rails" way to do it. :)

Upvotes: 4

Views: 282

Answers (1)

Bill Turner
Bill Turner

Reputation: 3697

Well, what in particular are you wanting to change in the associated query?

You can certainly do somethinglike this:

Bakery.find(:all, :include => :bakers, :conditions => ["bakers.something = ?", true])

If we had a little more info, there may be a better way to do it. Depending on what you're looking for, you may want to look into named_scopes, which you can chain together, like:

Bakery.bakers.available

named_scope is pretty neat.

Upvotes: 1

Related Questions