Bhushan Lodha
Bhushan Lodha

Reputation: 6862

Trouble passing value from view to controller in Rails 3.1.1

I have two model Product and Category, they have has_many, and belongs_to association respectively. Now, what I am trying to do is when I click on particular category I want all the products of that category to be listed. How do I do that

here is my view

 <p><%=link_to @product.category.name, show_by_category_products_path(@product.category.id)%> <%= @product.name%> <%[email protected]%><p>

and method in controller

  def show_by_category
   @products = Product.where("category_id=?", :id)
  end

Thanks! (I know its simple stuff, but sometimes you get blind and can't see a straightforward way so you have to sought help of others)

EDIT okay maybe I figured out a way to go around this.. but I am not sure if it is done in right way

Now my view and model looks something like this

<p><%=link_to @product.category.name, show_by_category_product_path(id: @product.id)%> <%= @product.name%>

def show_by_category
 @prod = Product.find(params[:id])
 @products = Product.where('category_id=?', @prod.category_id)
end

Tell me if this is right way?

Upvotes: 0

Views: 210

Answers (2)

Marnen Laibow-Koser
Marnen Laibow-Koser

Reputation: 6337

Your find should look more like Category.find(params[:id]).products. But try to follow RESTful routing principles, and nest your resources. Rails will do much more for you.

Upvotes: 1

Simon Perepelitsa
Simon Perepelitsa

Reputation: 20639

I would recommend you to read at least Getting Started guide, because you are doing it wrong.

Upvotes: 1

Related Questions