Rails:从一个查询中搜索多个表 [英] Rails: Searching multiple tables from one query

查看:44
本文介绍了Rails:从一个查询中搜索多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在findpaginate 方法中编写条件语句以允许用户在ProjectProject 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 names 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆