如何以find
或paginate
方式编写条件语句,以便用户同时搜索Project
和Project Category
个名称?
现在我的代码看起来像这样
@projects = Project.paginate :per_page => 20, :page => params[:page], :conditions => ['name LIKE ?', "%#{params[:search]}%"]
所以我还有Category
表和name
字段。如何在此搜索查询中将这两个name
组合在一起?
答案 0 :(得分:8)
假设您的Project
模型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'
根据需要更改上面的:order
。
答案 1 :(得分:0)
我愿意:
@categories = Category.find :conditions => ["name like ?", "%#{params[:search]}%"]
连接@projects和@categories,然后将结果用作最终搜索结果列表。