0

i want to implement a search that goes through multiple models.

Found this stackoverflow question here that uses ransack and tried it right away. But I can't seem to get it to work.

in my controller :

def search
  @quotes = Quote.search(title_cont: q).result
  @books = Book.search(title_cont: q).result
  @users = User.search(username_cont: q).result
end

routes

get '/search', to: 'application#search'

view

<%= form_tag search_path, method: :get do %>
  <%= f.label :title_cont %>
  <%= f.search_field :title_cont %>
  <%= text_field_tag :q, nil %>
<% end %>
Pavan
  • 33,316
  • 7
  • 50
  • 76
flenning12
  • 41
  • 8

2 Answers2

0

You should use params[:q] instead of q. This should work

def search
  @quotes = Quote.search(title_cont: params[:q]).result
  @books = Book.search(title_cont: params[:q]).result
  @users = User.search(username_cont: params[:q]).result
end

Also, f.label and f.search_field doesn't work with form_tag. You should use label_tag and search_field_tag instead

<%= form_tag search_path, method: :get do %>
  <%= label_tag :title_cont %>
  <%= search_field_tag :title_cont %>
  <%= text_field_tag :q, nil %>
<% end %>
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • I tried that but I dont see any results. Do I have to set up @results for that? And how would I show them on a result page? – flenning12 Oct 14 '18 at 10:54
  • @flenning12 I cant tell because I never worked with ransack, but I can give some pointers. Check this for a demo https://www.sitepoint.com/advanced-search-ransack/ – Pavan Oct 14 '18 at 11:08
0

Why do you have two fields in your search form, you should only have one search field.

<%= form_tag search_path, method: :get do %>
  <%= label_tag :title_cont %>
  <%= search_field_tag :q %>
<% end %>
Saqib Shahzad
  • 982
  • 12
  • 28