Make your links a product link, but add a category as a URL parameter.
Then in your controller, if the parameter is present, the filtering results on it. For instance:
View:
<h2> Find Product by Category </h2> <%= link_to "Electronics", products_path(:category=>"electronics")
controller
def index if params[:category] @products = Product.where(:category => params[:category]) else @products = Product.all end end
Based on egyamado's comment:
If you want to add flash messages, it will be something like this:
def index if params[:category] @products = Product.where(:category => params[:category]) flash[:notice] = "There are <b>#{@products.count}</b> in this category".html_safe else @products = Product.all end end
If you want to show the message only if there are no products, just add if @products.empty? at the end of the flash notation
Or you can make it completely conditional if you want to show an error message if there are no products and notice if there are products
def index if params[:category] @products = Product.where(:category => params[:category]) if @products.empty? flash[:error] = "There are <b>#{@products.count}</b> in this category".html_safe else flash[:notice] = "There are <b>${@products.count}</b> in this category".html_safe end else @products = Product.all end end
source share