我用下面的代码现在:如何使用Rails进行搜索?
def self.search(query)
where("name like ?", "%#{query}%")
end
只为名称的作品,但基本上我需要它的一切(的出生,姓,名+姓等等日期)工作。您能否告诉我一些想法,我可以如何让这段代码更适合我的需求?
谢谢。
我用下面的代码现在:如何使用Rails进行搜索?
def self.search(query)
where("name like ?", "%#{query}%")
end
只为名称的作品,但基本上我需要它的一切(的出生,姓,名+姓等等日期)工作。您能否告诉我一些想法,我可以如何让这段代码更适合我的需求?
谢谢。
在模型中,添加:
def self.search(cols, query)
tbl = self.arel_table
fq = tbl[cols.shift].matches("%#{query}%")
q = cols.inject(fq) do |acc, col|
acc.or(tbl[col].matches("%#{query}%"))
end
where(q)
end
然后你就可以使用它像:
User.search([:name, :surname], 'name')
将产生很好的SQL这样的:
SELECT "users".* FROM "users" WHERE (("users"."name" LIKE '%name%'
OR "users"."surname" LIKE '%name%'))
如果你需要更细控制您的查询,我有时会将以下便捷方法添加到AR中:
def self.arel_where(&block); where(yield self.arel_table); end
然后你可以这样做:
User.arel_where do |tbl|
name = '%name%'; surname = '%sur%'
tbl[:name].matches(name).and(tbl[:surname].matches(surname))
end
退房https://github.com/activerecord-hackery/meta_search – Nithin
这应该'在哪里(“名字怎么样?或者LIKE姓?或dob LIKE?“,”%#{query}%“,”%#{query}%“,”%#{query}%“)' – Pavan
我认为'dob'这个不行,如果'dob''datetime '列类型 –