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.
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 %>
Answering for anyone looking at this in 2019+... scenic is the gem you want to use (as long as your database is postgres).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With