nil的未定义方法`id':NilClass(Controller #create)

时间:2014-05-28 14:49:32

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

NameError in CommentsController#create undefined method `id' for nil:NilClass

以下行的错误。我想保存在当前时间授权的字段user_id(评论表)id用户中:

update_column(:user_id, user.id)

模型

class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :likes

  after_save :update_comments
  def update_comments
    update_column(:user_id, user.id)
    true
  end
end

class User < ActiveRecord::Base
  validates :name, presence: true, uniqueness: true
  has_secure_password
  has_many :comments
end

Comments_controller.rb

def create
    @user = User.all
    @comment = Comment.all
    @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

**视图/ _form **

<%= simple_form_for(@comment) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :text %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

节/新

<%= form_tag do %>
          <div class="as"><% if flash[:alert] %>
                <p id="notice"><%= flash[:alert] %></p>
            <% end %></div>
          <br><br>
          <fieldset>

            <legend></legend>
            <dl>
              <dt><label for="email">Log in:</label></dt>
              <dd><%= text_field_tag :name, params[:name], class: "user" %></dd>
            </dl>
            <dl>
              <dt><label for="password">Password:</label></dt>
              <dd><%= password_field_tag :password, params[:password], class: "password" %></dd>
            </dl>
          </fieldset>


          <fieldset class="action">
            <input type="submit" name="submit" id="submit" value="Enter" />
          </fieldset>
      <% end %>

1 个答案:

答案 0 :(得分:0)

尝试使用

def create
@user = User.all
@comment = Comment.all
@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

然后您无需明确将user_id分配给comment after_create。使用关联,它会自动将user_id分配给注释。