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)
No comments:
Post a Comment
Tell me what you think