如何解决错误(nil:NilClass 的未定义方法“名称”)

How to solve error (undefined method `name' for nil:NilClass)

我收到这个错误,如何解决这个关系错误

我有一个模型叫做 property.rb

class Property < ActiveRecord::Base
    belongs_to :rm
    belongs_to :category
end

我还有category.rb

class Category < ActiveRecord::Base
    has_many :rms,dependent: :destroy
    has_many :properties,dependent: :destroy
end

我的 RM(关系经理)模型是

class Rm < ActiveRecord::Base
  acts_as :user
  belongs_to :category
  has_many :properties
end

在我的控制器中,我列出了这样的属性

class Rms::PropertiesController < ApplicationController
  before_filter :authenticate_user!
  before_action :set_property, only: [:show, :edit, :update, :destroy]
  def index
    @properties = Property.all
  end
 def property_params
 params.require(:property).permit(:seller_name,:rm_id,:category_id,:property_type_id,:seller_email,:seller_phone,:property_name)
  end
end

在我的浏览页面 我列出了 RM 在 index.html.erb

中添加的 属性
    <% @properties.each do |property| %>
      <tr>
        <td><%= property.seller_name %></td>
        <td><%= property.seller_email %></td>
        <td><%= property.seller_phone %></td>
        <td><%= property.category.name %></td>
        <td><%= property.property_name %></td>
   <% end %>

确保 category 始终与 property 关联。

在属性模型中添加:

validates :category, presence: true

如果您的产品不一定总是有类别,您可以使用安全导航(这几乎总是一个丑陋的解决方案):

product.category.try(:name) # Ruby <  2.3.x
product.category&.name      # Ruby >= 2.3.x

undefined method `name' for nil:NilClass

这是因为 property 之一没有关联 category。立即解决方法是使用 try 方法。

<%= property.category.try(:name) %>

这是因为 property 没有与之相关联的 category。 所以

<td><%= property.category.name %></td>

抛出错误

undefined method `name' for nil:NilClass

因为 name 对于 nil class 不存在,在这种情况下是 category 您可以使用名为 andand 的 gem 来处理此类情况。 安装 gem 后只需将代码重写为:

<td><%= property.andand.category.name %></td>

可能是 属性 没有 category.Try 使用:

<%= property.category.name rescue nil%>