Hi,
I am using this code from railscast for searching in my activerecords:
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
On Jul 6, 2:57pm, Sebastian [email protected] wrote:
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’.
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
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