问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/22970699/rails-search-query-associated-model