Searching Multiple Models with Ransack Rails 4

2019-05-11 15:47发布

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条回答
Ridiculous、
2楼-- · 2019-05-11 16:38

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 %>
查看更多
登录 后发表回答