Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails filter index results by using a link (without dropdown)

If a user selects a predefined filter link, how would my index show results based on that request?

<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 would I make "Electronics" link to filter the products index to only include products with an "Electronics" category? The "category" field/column is already defined in my database/model.

This is currently what my controller looks like:

def index
  @products = Product.all
end

Thanks.

like image 383
docta_faustus Avatar asked Nov 04 '13 01:11

docta_faustus


1 Answers

Make your links a link back to the products, but add category as a url parameter.

Then in your controller, if the parameter is present, filter results based on it. Such as:

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 comment by egyamado :

If you want to add flash messages it would 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 only want to show the message if there are no products, then just add if @products.empty? to the end of the flash designation

Or you could make it completely conditional if you want to show an error message if there are no products and a 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
like image 164
trh Avatar answered Oct 06 '22 19:10

trh