Rails: Searching multiple tables from one query

只谈情不闲聊 提交于 2020-01-01 07:05:34

问题


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]}%"]

So I have also Category table with name field. How do I combine those two names together in this search query?


回答1:


Assuming that your 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.




回答2:


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.



来源:https://stackoverflow.com/questions/652933/rails-searching-multiple-tables-from-one-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!