I have set up a simple search from Ryan Bate's rails casts: http://railscasts.com/episodes/37-simple-search-form
After the search results show, I would like to have a few links that can sort the already searched information. For my Product model they search by name and get results. I would like to have category links under the search so they can then filter their search results by category. controller is straight forward:
def index
@products = Product.search(params[:search])
#scope filtering
if params[:toys]
@products = Product.toys
end
end
I have added scopes in the model, but am not sure how to combine the SQL statement for the scopes and the search.
class Product < ActiveRecord::Base
scope :electronics, -> { where(category: 'electronics') }
scope :toys, -> { where(category: 'toys') }
def self.search(term)
where("name like :term", term: "%#{term}%")
end
end
And the view: index.html.erb
<%= form_tag products_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<%= link_to 'Electronics', products_path(:electonrics => true) %> | <%= link_to 'Toys', products_path(:toy => true) %>
Basically when I search the form goes to localhost:3000/products?utf8=✓&search=foo gets all the results for foo as it should. Then when I click filter only electronics after the search I need some sort of join or union to make the search localhost:3000/products?utf8=✓&search=foo&category=toys.
If there is an easier way to sort by category after the user has searched some field, I'm sure I and others learning ruby on rails would be thankful to see a more ruby way to solve the problem.