2015-05-31 70 views
1

我有以下設置:Ruby on Rails的未定義的方法'標題」的零:NilClass

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.products.each do |p| %> 

    <article class="content-block"> 
     <h3><%= @p.title %></h3> 
    </article> 

<% end %> 

這將返回錯誤的稱號。我在這裏做錯了什麼?

回答

4

它應該是:

<h3><%= p.title %></h3> # as, your block variable is p, not @p 

<h3><%= @p.title %></h3> 

一個建議,你可以寫你的set_category方法,如:

def set_category 
    @category = Category.includes(:products).find(params[:id]) 
end 

這將解決使用N + 1問題渴望加載協會技術。

相關問題