使用 Ransack 一次搜索多个模型 [英] Search multiple models at once with Ransack
问题描述
我的应用标题中有一个搜索表单,我想使用此搜索表单来搜索应用中的多个模型.
I have a search form in the header of my app and I would like to use this search form to search through multiple models within the application.
例如,像 /search?q=rails
这样的请求应该触发对多个模型的搜索,比如 Work
、Project
、User
及其定义的属性.我想使用 Ransack,因为我已经在应用不同区域的 Work
模型上使用了它.
For example a request like /search?q=rails
should trigger a search through multiple models like Work
, Project
, User
and their defined attributes. I wanted to use Ransack because I already use it on the Work
model in a different area of the app.
我想我还不太了解 Ransack 并且文档总是指出你必须定义 @q = MyModel.search(params[:q])
以在表单中使用它search_form_for @q
.有没有一种方法可以让您不必提前定义特定模型?只需传入参数名称,如 search_form_for :q
?
I think I don't quite understand Ransack yet and the documentation always points out that you have to define @q = MyModel.search(params[:q])
to use it in the form search_form_for @q
. Is there a way where you don't have to define a specific model in advance? And just pass in the parameter name like search_form_for :q
?
推荐答案
好吧,问完这个问题我的脑子里就蹦出来了.
Okay, after asking the question the answer popped into my head.
代替 search_form_for
助手,我现在只是通过以下方式使用 form_tag
助手:
Instead of the search_form_for
helper I'm now just using the form_tag
helper in the following way:
<%= form_tag search_path, method: :get do %>
<%= text_field_tag :q, nil %>
<%= end %>
在搜索操作中我只做:
q = params[:q]
@works = Work.search(name_cont: q).result
@projects = Project.search(name_cont: q).result
@users = User.search(name_cont: q).result
这对我有用.我希望这也能帮助其他人.
This works for me. I hope this also helps someone else.
这篇关于使用 Ransack 一次搜索多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!