Reputation: 7003
I have the following setup:
Product.rb
class Product < ActiveRecord::Base
belongs_to :category
end
Category.rb
class Category < ActiveRecord::Base
belongs_to :category
has_many :categories
has_many :products
end
categories_controller.rb
def show
end
private
def set_category
@category = Category.find(params[:id])
end
def category_params
params.require(:category).permit(:title, :category_id)
end
products_controller.rb
def product_params
params.require(:product).permit(:title, :price, :text, :category_id, :avatar)
end
Category show
<% @category.products.each do |p| %>
<article class="content-block">
<h3><%= @p.title %></h3>
</article>
<% end %>
And this returns the error in the title. What have I done wrong here?
Upvotes: 1
Views: 401
Reputation: 118271
It should be :
<h3><%= p.title %></h3> # as, your block variable is p, not @p
NOT
<h3><%= @p.title %></h3>
One more suggestion, you could write your set_category
method, as:
def set_category
@category = Category.includes(:products).find(params[:id])
end
It will solve N + 1 problems using Eager Loading Associations technique.
Upvotes: 4