Search across associations

Hello:

I’m pretty new to mysql and need to build a search function that
searches fields in a ‘case’ object as well as fields in ‘person’ objects
that reference each ‘case’ object. The function must return a single
array of ‘case’ objects.

Searching for fields in the case object seems pretty straightforward:

def search
@cases = Case.find(:all, :conditions => [“lower(field_1) like ? OR
lower(field_2) like ?”, “%” + params[:search].downcase + “%”, “%” +
params[:search].downcase + “%”])
render :partial => ‘cases’, :collection => @cases
end

But I can’t figure out how to search objects that ‘belong_to’ the case
object.

But I can’t figure out how to search objects that ‘belong_to’ the case
object.

Posted viahttp://www.ruby-forum.com/.

It seems like what you are trying to do is search the person fields
for a string. That is going to return Person records. You then want
an array of the cases associated with the persons that were returned
from the search string. Is that correct?

Greg DeVore

On 22 Dec 2007, at 00:41, Peter M. wrote:

def search
@cases = Case.find(:all, :conditions => [“lower(field_1) like ? OR
lower(field_2) like ?”, “%” + params[:search].downcase + “%”, “%” +
params[:search].downcase + “%”])
render :partial => ‘cases’, :collection => @cases
end

But I can’t figure out how to search objects that ‘belong_to’ the case
object.

You can do Case.find :all, :include => :person, :conditions =>
[‘cases.foo = ? or people.bar = ?’, …]
In rails 2 you can use :joins instead of :include if you’re not
interested in actually eager loading the :person associations.
And you’ve always been able to Case.find :all, :joins => “some fancy
bit of sql to join the people table in the desired way”, :conditions
=> [‘cases.foo = ? or people.bar = ?’, …]
(you almost always want to specify a :select option if you do tha)

Fred

Frederick C. wrote:

You can do Case.find :all, :include => :person, :conditions =>
[‘cases.foo = ? or people.bar = ?’, …]
In rails 2 you can use :joins instead of :include if you’re not
interested in actually eager loading the :person associations.
And you’ve always been able to Case.find :all, :joins => “some fancy
bit of sql to join the people table in the desired way”, :conditions
=> [‘cases.foo = ? or people.bar = ?’, …]
(you almost always want to specify a :select option if you do tha)

Fred

This is exactly what I was looking for. God I love rails. Thanks a lot
guys.

Peter

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs