Searching Multiple Models with Ransack Rails 4

徘徊边缘 提交于 2019-12-12 09:53:20

问题


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 

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 %>

I added a route:

get "search" => "search#index"

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.

Thanks!


回答1:


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

Alternatively, you could combine your results @results = @items + @booths + @users and then:

<% @results.each do |result| %>
  # display the result
<% end %>


来源:https://stackoverflow.com/questions/27512084/searching-multiple-models-with-ransack-rails-4

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