Reputation: 51
I have a similar question to this but still can't figure it out.
I am creating a rails app linked to a Neo4j database and have a number of models I want to search across with one search form. I am using elastic search.
My current code for searching within one model (works fine):
#/app/views/symptoms/index.html
<%=form_tag symptoms_path, class: "form-inline", method: :get do %>
<div class="form-group">
<%= text_field_tag :query, params[:query], class: "form-control" %>
<%= submit_tag "Search", class: "btn btn-primary" %>
<% if params[:query].present? %>
<%= link_to "clear" %>
<% end %>
</div>
<% end %>
#/app/controllers/symptoms_controller.rb
def index
if params[:query].present?
@symptoms = Symptom.search(params[:query], show: params[:show])
else
@symptoms = Symptom.all
end
end
Currently this will only search within the symptoms model. I want to to create a 'global search' field that will search within the symptoms_path, allergies_path, and drugs_path.
Potential 'Global Search' code:
#/app/views/global_search/index.html
<%=form_tag [symptoms_path, allergies_path, drugs_path], class: "form-inline", method: :get do %>
<div class="form-group">
<%= text_field_tag :query, params[:query], class: "form-control" %>
<%= submit_tag "Search", class: "btn btn-primary" %>
<% if params[:query].present? %>
<%= link_to "clear" %>
<% end %>
</div>
<% end %>
#/app/controllers/symptoms_controller.rb
def index
if params[:query].present?
@allergies = Allergy.search(params[:query], show: params[:show])
@drugs = Drug.search(params[:query])
@symptoms = Symptom.search(params[:query])
else
@allergies = Allergy.all
@drugs = Drug.all
@symptoms = Symptom.all
end
end
Any ideas for how I could implement this? Thanks in advance!
Upvotes: 1
Views: 477
Reputation: 10856
I'd probably suggest that you create something like a "search_controller" (rails generate controller search
should help you do that). In there you can have an index
action (or whatever you want to call your action) and then you just set up a route to point a URL to it such as this:
# config/routes.rb
# Link the URL to the search controller's `index` action
post '/search/:query' => 'search#index'
# app/controllers/search_controller.rb
def index
if params[:query].present?
@allergies = Allergy.search(params[:query], show: params[:show])
@drugs = Drug.search(params[:query])
@symptoms = Symptom.search(params[:query])
else
@allergies = Allergy.all
@drugs = Drug.all
@symptoms = Symptom.all
end
end
Sorry if I'm misunderstanding, I'm not sure how much you've worked with Rails before
Upvotes: 1