使用 Ransack Rails 4 搜索多个模型 [英] Searching Multiple Models with Ransack Rails 4
问题描述
我想弄清楚如何使用 Ransack 搜索多个模型.目标是在我的共享标题中包含搜索表单.我正在使用他们的文档、旧的 rails-cast、SO 问题和朋友与我共享的一些代码的组合.现在我认为它有效,虽然我不确定,因为我无法在我的索引页面上显示结果.
I'm trying to figure out how to search multiple models with Ransack. The goal is to have the search form in my shared header. I'm using a combination of their documentation, an old rails-cast, SO questions, and some code a friend shared with me. Right now I think it works, although I'm not sure because I can't get the results to show on my index page.
首先,我创建了一个搜索控制器:
First, I created a search controller:
class SearchController < ApplicationController
def index
q = params[:q]
@items = Item.search(name_cont: q).result
@booths = Booth.search(name_cont: q).result
@users = User.search(name_cont: q).result
end
end
接下来,我把这段代码放在头部部分(views/layouts/_header.html.erb)中:
Next, I put this code in the header partial (views/layouts/_header.html.erb):
<%= form_tag search_path, method: :get do %>
<%= text_field_tag :q, nil %>
<% end %>
我添加了一条路线:
get "search" => "search#index"
我的搜索控制器的 index.html.erb 是空的,我怀疑这就是问题所在,但我不确定在那里放什么.当我尝试以下操作时:
My index.html.erb for the Search controller is empty and I suspect that is the problem, but I'm not sure what to place there. When I try something like:
<%= @items %>
<%= @users %>
<%= @booths %>
这是我执行搜索时得到的输出:
This is the output I get when I execute a search:
#<Item::ActiveRecord_Relation:0x007fee61a1ba10> #<User::ActiveRecord_Relation:0x007fee61a32d28> #<Booth::ActiveRecord_Relation:0x007fee61a20790>
有人可以指导我解决方案吗?我不确定这是索引视图问题、路由问题还是其他问题.在所有教程中,搜索字段和结果仅适用于一个模型,因此我对如何跨多个模型实现这一点感到有些困惑.
Can someone please guide me on what the solution might be? I'm not sure if it's an index view problem, routing problem, or something else. On all of the tutorials the search field and results are only for one model so I'm a little confused on how to pull this off across multiple models.
谢谢!
推荐答案
您得到的输出是正确的.这些变量中的每一个都包含一个 ActiveRecord_Relation
对象,可以将其视为一个数组.通常你会做这样的事情:
The output you are getting is correct. Each of those variables contains an ActiveRecord_Relation
object which can be treated like an array. Normally you'd do something like:
<% @items.each do |item| %>
<%= item.name %> # or whatever
<% end %>
<% @users.each do |user| %>
# and so on
或者,您可以组合您的结果 @results = @items + @booths + @users
然后:
Alternatively, you could combine your results @results = @items + @booths + @users
and then:
<% @results.each do |result| %>
# display the result
<% end %>
这篇关于使用 Ransack Rails 4 搜索多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!