Finding Multiple Models with Ransack Rails 4

I am trying to figure out how to search multiple models using Ransack. The goal is to have a search form in my general title. I use a combination of their documentation, old rails-cast, SO-questions and code that a friend shared for me. Right now I think it works, although I'm not sure because I can't show the results on my index page.

I first 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 

      

Then I put this code in a partial header (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 this is the problem, but I'm not sure what to put in there. When I try something like:

<%= @items %>
<%= @users %>
<%= @booths %>

      

This is the result I get when doing a search:

#<Item::ActiveRecord_Relation:0x007fee61a1ba10> #<User::ActiveRecord_Relation:0x007fee61a32d28> #<Booth::ActiveRecord_Relation:0x007fee61a20790>

      

Can anyone please guide me on what might be a solution? I'm not sure if this is an index view issue, a routing issue, or something else. All tutorials show the search box and results for only one model, so I'm a little confused about how to do this for multiple models.

Thank!

+3


source to share


1 answer


The result you are getting is correct. Each of these variables contains an object ActiveRecord_Relation

that can be thought of as an array. You usually do something like:

<% @items.each do |item| %>
  <%= item.name %> # or whatever
<% end %>
<% @users.each do |user| %>
# and so on

      



Alternatively, you can combine the results @results = @items + @booths + @users

and then:

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

      

+3


source







All Articles