Jack Gruber
Jack Gruber

Reputation: 163

Ransack Ruby On Rails Result Wont Render

I have been trying to implement the Ransack search gem into a project I am currently working on. I am pretty sure that I have it set up correctly. I want to be able to search profiles and have placed my code in the profiles controller like so:

def index
 @q = Profile.search(params[:q])
 @profile = @q.result(distinct: true)
 @profiles = Profile.all
end

And the profile index.html.erb file like so:

<%= search_form_for @q do |f| %>
 <div class="field">
 <%= f.label :first_name_cont, "Name Contains" %>
 <%= f.search_field :first_name_cont %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>

It does at the least appear to be attempting to search database correctly but just wont render any results on screen. It might be something obvious I am just not seeing. Any help is greatly appreciated.

Upvotes: 0

Views: 214

Answers (2)

Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Try a set up like this in your controller and view:

 #profile controller
  def index
    @search = Profile.search(params[:q])
    @profiles = @search.result(distinct: true)
  end

  #profile index
  <%= search_form_for @search do |f| %>
    <%= f.label :first_name_cont, "name in profile" %><br>
    <%= f.submit "Search", class:"btn btn-info btn-block" %>
  <% end %>

  <% @profiles.each do |profile| %>
    <%= profile.name %>
  <% end %>

Upvotes: 1

bri
bri

Reputation: 1

Is the problem when you try to access @profile or just is it with knowing how to display results? If the latter, right now they are being stored in @profile so you need to loop through them and choose what you want to show from each profile instance.

From when I've used this gem it seems it defaults to the index page of the given class (so in your case, the profile index page). So you can either:

  1. Just let the results list below the search form you shared above.
  2. Move the search bar to something like a homepages controller so when a search is made it'll go to the profile index page and only show the results.

Upvotes: 0

Related Questions