[英]Rails Search Query Associated Model
In railscast #37 they show a simple search I am trying to implement.在railscast #37 中,他们展示了我正在尝试实施的简单搜索。 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. Dog 模型有一个属性“name”,所有者也是。 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.
我需要能够过滤狗的列表,以便如果您输入“Fido”(狗)或“Bob”(所有者)Fido 将显示在列表中。 Here is how the search is currently set up:
以下是当前设置的搜索方式:
model dog.rb:模型狗.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.假设按照Rails约定你有一个名为表
dogs
的Dog
模型和owners
对Owner
的模型。
Update the search
method as below:更新
search
方法如下:
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您需要在
dogs
和owners
表之间进行连接查询才能访问owners.name
字段
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.