Ruby on Rails undefined method `title' for nil:NilClass -
i have 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 |p| %> <article class="content-block"> <h3><%= @p.title %></h3> </article> <% end %>
and returns error in title. have done wrong here?
it should :
<h3><%= p.title %></h3> # as, block variable p, not @p
not
<h3><%= @p.title %></h3>
one more suggestion, write set_category
method, as:
def set_category @category = category.includes(:products).find(params[:id]) end
it solve n + 1 problems using eager loading associations technique.
Comments
Post a Comment