【问题标题】:Ruby on Rails undefined method `title' for nil:NilClassRuby on Rails 未定义方法 `title' 用于 nil:NilClass
【发布时间】:2015-05-31 15:32:08
【问题描述】:

我有以下设置:

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 %>

这会返回标题中的错误。我在这里做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4.2


    【解决方案1】:

    应该是:

    <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
    

    它将使用 Eager Loading Associations 技术解决N + 1 问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多