Rails 3 where query for nested attributes

156 views
Skip to first unread message

Sebastian

unread,
Jul 6, 2011, 9:57:16 AM7/6/11
to Ruby on Rails: Talk
Hi,

I am using this code from railscast for searching in my activerecords:
http://railscasts.com/episodes/37-simple-search-form

There is this method in the 'Product'-Model, which is searching for
the product name:

class Project < ActiveRecord::Base
has_many :tasks
validates_presence_of :name

def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"]) #Rails
2
where('name LIKE ?', "%#{search}%") #Rails 3
else
find(:all)
end
end
end

My question is now, how can I search for products that have a given
task name. Task is a nested attribute for Product. I only use one of
the search line above. The second one is only possible with Rails 3.

I don't find anything about nested queries for activerecords with
'find' or 'where'.

I hope someone can help!
Sebastian

Frederick Cheung

unread,
Jul 6, 2011, 11:37:35 AM7/6/11
to Ruby on Rails: Talk
You can do stuff like Project.joins(:tasks).where(:tasks =>
{:some_column_on_tasks = 23}) (in rails to that would be
find :all, :joins => :tasks, :conditions => {:tasks => {...}}

If you use the string form of conditions you just need to prepend the
table name to the column name, ie where('tasks.name like ...')

Fred

Sebastian

unread,
Jul 12, 2011, 3:27:55 AM7/12/11
to Ruby on Rails: Talk
Thank you so much, it's working great! I also found that in the
official Rails 3 guides, but I didn't know that I have to look for the
join method.

Now I am using the following code, just for case that anybody else
has the same issue:

class Project < ActiveRecord::Base
has_many :tasks
validates_presence_of :name

def self.search(search)
if search
joins(:tasks).where('name LIKE ?', "%#{search}%") #Rails 3
else
find(:all)
end
end
end

Reply all
Reply to author
Forward
0 new messages