Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search Multiple models in ruby on rails

I am still a beginner in ruby on rails and I'm trying to create a simple search option for a website that I'm developing.

I have number of models such as Sundries, Curry and Starter.

My search works fine if I have one model but how do I search all models title or name?

I have added following method to each of the models and tried to display results in home page. but no luck!

def self.search(search)
where("LOWER(title) LIKE ?", "%#{search.downcase}%") 
#where("content LIKE ?", "%#{search}%")
end

Can someone please help me figure this out with an example please?

Thank you.

like image 559
roshiend Avatar asked Oct 26 '16 13:10

roshiend


3 Answers

You can add ActiveRecord_Relations together, and it will give you a simple array

@results = Sundries.search(search_term) + Curry.search(search_term) + Starter.search(search_term)

In the view...

<% @results.each do |result| %>
  <%= "#{result.title} part of our fine #{result.class.name} choices" %>
<% end %>
like image 150
SteveTurczyn Avatar answered Sep 29 '22 05:09

SteveTurczyn


Answering for anyone looking at this in 2019+... scenic is the gem you want to use (as long as your database is postgres).

like image 20
deepmotion Avatar answered Sep 29 '22 04:09

deepmotion


There are several approaches how you can implement this. You can use advanced search engines such as ElasticSearch or Sphinx. Or you can use (for example) pg_search gem in case you are using Postgresql as your DataBase.

You can find RailsCasts for each of these approaches (some of them are probably for subscribers only).

As soon as you learning Rails, I would recommend to try out pg_search at first and avoid using search engines. Because it can be tricky sometimes for beginners. You can get to them later than you will have more data in your DB, or you would need to improve your skills. Try to make working solution in the first place and then improve it.

like image 40
ck3g Avatar answered Sep 29 '22 05:09

ck3g