I am trying to create a view where I can see all products that belong
to a certain category.
My models have the following relationships:
Category: has_many :products
Product: belongs_to :category
Both category_controller.rb and product_controller.rb are in my admin
area and need Admin login to edit/delete…
I am also using a catalog_controller.rb to view all my products.
In my catalog_controller.rb I created the following:
btw, you can also eliminate @products altogether and just use @category.products.each do |product| in your view.
You can do that, but I don’t advise it. I think the code is easier to
deal with when all queries are executed in the controller, and all the
view does is render things that the controller has set up. It certainly
makes your code easier to test, since you can check assigns(:products)
in the test method.
It’s hard to say without seeing your full controller method, and your
category / product models and your database data. Try using
script/console to play around with the relationships and debug it there.
Try:
/script/console
then:
c = Category.find(1) #(or whatever category id you are looking at now)
then:
c.products
None-the-less, playing with it in script/console will help you narrow it
down, and if it works as expected there, the problem must be in your
controller and / or view code somewhere.
You can do that, but I don’t advise it. I think the code is easier to
deal with when all queries are executed in the controller, and all the
view does is render things that the controller has set up. It certainly
makes your code easier to test, since you can check assigns(:products)
in the test method.
Could I ask (what might be a silly question) how would you run the
query in the controller? and how would I change my code in my view?
None-the-less, playing with it in script/console will help you narrow it
down, and if it works as expected there, the problem must be in your
controller and / or view code somewhere.
It worked in the console. I changed it to this:
<%= product.title %>
and it worked. :))))
I then changed it to be a link: <%= link_to product.title, :action =>
“show”, :id => product %>
btw, the reason that Category.products didn’t work is because the
has_many association adds an instance method to the Category model, not
a class method, so Category.products is not a method, but c =
Category.find(:first); c.products is.
Hope this helps.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.