BACKTRACE

(condense)

Back to Posts List

GET

Rails Conditional Eager Loading

Rails’s eager loading (ScreenCast) is an important practice that saves some requests and queries when dealing with table relations in rails.
Up until now, using a condition hash to specify query was a little tricky if you use the eager loading method:


User.find(:all, :include => :jobs, :conditions => [“jobs.salary > ?”,1000])

or using a hash (without eager loading)

User.find(:all, :conditions => {:name => ’eizesus’})

Using a conditions array/hash isnít always my favorite way to write finds in Rails, but in certain cases must have when you deal with complex queries (like and “Advanced Search” feature).

In my current work,I needed to run conditions on an associated table in just such an “Advanced search” feature, so i came up with this simple and easy way to use a condition hash for eager loading methods:

User.find(:all, :include => :jobs, :conditions => {:name => ‘eizesus’, :jobs => {:position => ’Manager’})


or you can prepare the condition hash on the fly:

conditions = {}
conditions[:first_name] = params[:first_name] unless params[:first_name].blank?
conditions[:last_name] = params[:last_name] unless params[:last_name].blank?
conditions[:jobs] = {:position => params[:position]} unless params[:position].blank?

@users = User.find(:all, :conditions => conditions, :include => :jobs)

POST

blog comments powered by Disqus

I Don't have cookies.

ELAD ENV

Variable Value
LINKEDIN
TWITTER
FACEBOOK
GITHUB
WWR
IRC
{ 'irc.freenode.net' => [ '#rubyonrails', '#railsbridge', '#ruby', '#mootools' ]}
SKYPE
eladmeidar

You're seeing this error because I think it is funny.