flenning12
flenning12

Reputation: 41

Ruby on Rails ransack gem search

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

Upvotes: 0

Views: 479

Answers (2)

Saqib Shahzad
Saqib Shahzad

Reputation: 1002

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

Upvotes: 0

Pavan
Pavan

Reputation: 33542

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

Upvotes: 0

Related Questions