Rails:从一个查询中搜索多个表 [英] Rails: Searching multiple tables from one query
问题描述
如何在find
或paginate
方法中编写条件语句以允许用户在Project
和Project Category
中搜索> 同时命名?
How do I write condition statement in find
or paginate
method to allow users search in Project
and Project Category
names simultaneously?
现在我的代码看起来像这样
Now my code looks like this
@projects = Project.paginate :per_page => 20, :page => params[:page], :conditions => ['name LIKE ?', "%#{params[:search]}%"]
所以我还有带有 name
字段的 Category
表.我如何在此搜索查询中将这两个 name
组合在一起?
So I have also Category
table with name
field. How do I combine those two name
s together in this search query?
推荐答案
假设你的 Project
模型 has_many :categories
:
@projects = Project.paginate :per_page =>20, :page =>params[:page], :joins =>:categories, :conditions =>['projects.name LIKE ?OR category.name LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%"], :order =>'projects.id DESC'
如果/根据需要更改上面的 :order
.
Change the :order
above if/as needed.
这篇关于Rails:从一个查询中搜索多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!