Search multiple models at once with Ransack
Asked Answered
T

1

20

I have a search form in the header of my app and I would like to use this search form to search through multiple models within the application.

For example a request like /search?q=rails should trigger a search through multiple models like Work, Project, User and their defined attributes. I wanted to use Ransack because I already use it on the Work model in a different area of the app.

I think I don't quite understand Ransack yet and the documentation always points out that you have to define @q = MyModel.search(params[:q]) to use it in the form search_form_for @q. Is there a way where you don't have to define a specific model in advance? And just pass in the parameter name like search_form_for :q?

Trounce answered 27/5, 2013 at 14:20 Comment(0)
T
46

Okay, after asking the question the answer popped into my head.

Instead of the search_form_for helper I'm now just using the form_tag helper in the following way:

<%= form_tag search_path, method: :get do %>
  <%= text_field_tag :q, params[:q] %>
<%= end %>

and in the search action I just do:

q = params[:q]
@works    = Work.search(name_cont: q).result
@projects = Project.search(name_cont: q).result
@users    = User.search(name_cont: q).result

This works for me. I hope this also helps someone else.

Trounce answered 27/5, 2013 at 14:28 Comment(2)
Here in 2021 to say still a brilliant and simple solutionArarat
It's still great in 2023, but it bears mentioning that apparently the syntax has changed a little. "ransack" instead of "search" worked for me.Overcast

© 2022 - 2024 — McMap. All rights reserved.