nil的未定义方法`first_name':NilClass - 这不是Nil

时间:2014-01-03 12:44:13

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

用户有很多评论,评论属于很多用户。如何解决此错误?

  

nil的未定义方法`first_name':NilClass

当我尝试

   <h3>Comments</h3>
     <% @guide.comments.each do |comment| %>
       <div>
         <p><%= comment.user.first_name %></p>
       </div>
     <% end %>

user.rb

has_many :comments

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :user
end

评论迁移(我添加了一个user_id列):

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :body
      t.integer :user_id

      t.timestamps
      add_foreign_key :comments, :guides
    end
  end
end

评论控制器:

def create
    @comment = Comment.new(comment_params)

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
        format.json { render action: 'show', status: :created, location: @comment }
      else
        format.html { render action: 'new' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

6 个答案:

答案 0 :(得分:1)

很久以前,但对于有相同错误的人来说这可能很有用。 您应该delegate first_nameuser并允许nil

class Comment < ActiveRecord::Base
  belongs_to :user
  delegate :first_name, to: :user, allow_nil: true, prefix: true
end

然后使用

在视图中调用它
<h3>Comments</h3>
  <% @guide.comments.each do |comment| %>
    <div>
      <p><%= comment.user_first_name %></p>
    </div>
  <% end %>

如果没有用户,那么它将不显示任何内容而不会引发异常

答案 1 :(得分:0)

我猜你在创建评论对象时没有设置用户ID。你可以试试下面的代码吗?

def create
    @comment = current_user.comments.new(comment_params)

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
        format.json { render action: 'show', status: :created, location: @comment }
      else
        format.html { render action: 'new' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

答案 2 :(得分:0)

确保您的用户模型具有first_name属性。然后确认您的评论记录实际上有一个与之关联的用户。您可能没有在Comment类中将user_id列列入白名单,因此未设置用户

class Comment
  attr_accessible :user_id, ...
end

或者在rails 4中,你有强大的参数而不是attr_accessible

How is attr_accessible used in Rails 4?

答案 3 :(得分:0)

模型没有找到comment.user。可能是注释的user_id尚未设置或user_id未在“user”表“id”列中显示。您可以打印注释ID和comment.user_id并签入DB。

你设置:

has_many :comments, :dependent => :destroy

或者它可能会让你删除用户,但用户的评论仍然存在,那么对于这些​​评论,comment.user为空。

答案 4 :(得分:0)

您确定在创建评论时设置了user_id吗? 也许控制器中缺少这条简单的线

    @comment.user = current_user

为了确保评论中有用户,您应该添加评论模型

validates_presence_of :user_id

并在您的用户模型中

has_many :comments, :dependent => :destroy

答案 5 :(得分:-1)

在Ruby中定义方法非常简单。要解决您的问题,请定义

class << nil
  def first_name; "John" end
  def last_name; "Doe" end
end

错误将消失。所有nil对象现在都被命名为“John Doe”。