[英]Rails: Searching multiple tables from one query
How do I write condition statement in find
or paginate
method to allow users search in Project
and Project Category
names simultaneously?如何在
find
或paginate
方法中编写条件语句以允许用户同时搜索Project
和Project Category
名称?
Now my code looks like this现在我的代码看起来像这样
@projects = Project.paginate :per_page => 20, :page => params[:page], :conditions => ['name LIKE ?', "%#{params[:search]}%"]
So I have also Category
table with name
field.所以我也有
name
字段的Category
表。 How do I combine those two name
s together in this search query?如何在此搜索查询中将这两个
name
组合在一起?
Assuming that your Project
model has_many:categories
:假设您的
Project
model has_many:categories
:
@projects = Project.paginate:per_page => 20, :page => params[:page], :joins =>:categories, :conditions => ['projects.name LIKE? OR categories.name LIKE?', "%#{params[:search]}%", "%#{params[:search]}%"], :order => 'projects.id DESC'
Change the :order
above if/as needed.如果/根据需要更改上面的
:order
。
I would do:我会做:
@categories = Category.find :conditions => ["name like ?", "%#{params[:search]}%"]
Concatenate @projects and @categories, and then use the result as the final search result list.连接@projects 和@categories,然后将结果作为最终的搜索结果列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.