简体   繁体   中英

Rails Search Query Associated Model

In railscast #37 they show a simple search I am trying to implement. I have the following association:

class Owner < ActiveRecord::Base
    has_many :dogs
end

class Dog < ActiveRecord::Base
    belongs_to :owner
end

The Dog model has an attribute "name" and so does the owner. I need to be able to filter a list of dogs so that if you type "Fido" (dog) or "Bob" (owner) Fido will show up in the list. Here is how the search is currently set up:

model dog.rb:

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

this will return ONLY search terms matching the dog name (owner name is ignored)

I tried to change it to something like this:

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

However is says there is no owner column. How do I change the search condition to be able to search both dog name and owner name?

Assuming that by following Rails convention you have tables named dogs for Dog model and owners for Owner model.

Update the search method as below:

  def self.search(search)
    if search
      joins(:owner).where('dogs.name LIKE ? or owners.name LIKE ?', "%#{search}%", "%#{search}%")
    else
      find(:all)
    end
  end

You need a join query between dogs and owners table in order to access owners.name field

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM