Jack Gruber Jack Gruber - 18 days ago 7
Ruby Question

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.

Answer

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