Rails filter index results using a link (no drop-down list)

If a user selects a predefined filter link, how will my index show results based on this query?

<h1>Products</h1> <% @products.each do |product| %> <%= link_to product.name, product_path(product) %> <% end %> <h2>Find Product by Category</h2> Electronics Apparel Books 

For example, how can I make an Electronics link to filter the product index only for products with the Electronics category? The field / column "category" is already defined in my database / model.

Currently my controller is as follows:

 def index @products = Product.all end 

Thanks.

+6
source share
2 answers

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 
+13
source

Thank you so much for the message. It was perfect for my needs.

I use it in the link <td><%= link_to 'Show', candidates_path(:atc_name=>(atc.name)) %></td> .

0
source

Source: https://habr.com/ru/post/957311/


All Articles