0
votes

I have a store application with a Product scaffold and I want to enable categories and pages that show each category of products.

My product model has a "category" attribute and I use the link_to helper to create links to each category.

In my products controller I added a method called index_by_category(cat):

def index_by_category(cat)    
  @products_by_category = Product.where(category: cat)
end

I'm trying to iterate @products_by_category in a view I created with the corresponding name (product/index_by_category.html.erb) just like the regular index method do. For some reason it render me the regular index method of products which shows ALL of them, even though the URL is:

http://localhost:3000/products?index_by_category=Food

This is what I did in my route.rb file:

get 'products/index_by_category'

I'm newbie to Rails development so if I did something which is wrong from the roots and the rails approach to the problem should be entirely different I also be happy to know for the sake of learning.

1
Add get 'products/index_by_category' before this line resources :products in your routes.rb file and then to check that route really exists, open a console and navigate to your project folder and run bundle exec rake routes | grep index_by_category cristian
I recommendet to change the position of your route definition because Rails routes are matched in the order they are specifiedcristian
@cristian it didn't solved the issue when I changed where I routed the function. However the second solution in the answer below did the work. Thank you!Maboo

1 Answers

1
votes

You are doing things a bit wrong. Try to write your controller like this:

def index_by_category   
  @products_by_category = Product.where(category: params[:category])
end

And update your route

get 'products/category/:category', to: 'products#index_by_category

Then visit

http://localhost:3000/products/category/Food

UPDATE

if you really want to use index method for both cases you could do that by modifying it to something like this

def index
  if params[:category]
    @products = Product.where(category: params[:category])
  else
    @products = Product.all
  end
end

and then just visit

http://localhost:3000/products?category=Food