NoMethodError(未定义的方法`user_id ='对于nil:NilClass):在文章控制器中

时间:2017-12-23 09:32:42

标签: ruby-on-rails ruby

我正在尝试实现创建新文章的功能。但是,当我单击“提交”按钮时,它会出现以下错误。

Started POST "/articles" for 127.0.0.1 at 2017-12-23 14:04:29 +0500
Processing by ArticlesController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"lbrD/8QZAlLuxVbw3vmRuKI20zkrckYut4nebyW5hLk6EFkODh4d0IAZ6yms2oRkWGqE3eWlUQwBUrfu1SiAnw==", "article"=>{"title"=>"AYYE", "text"=>"Ma ka "}, "commit"=>"Create Article"}
  User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 13], ["LIMIT", 1]]
Completed 500 Internal Server Error in 6ms (ActiveRecord: 0.6ms)



NoMethodError (undefined method `user_id=' for nil:NilClass):

app/controllers/articles_controller.rb:26:in `create'

这是create方法:

def create
    @article.user_id = current_user.id
      if @article.create
         redirect_to @article
      else
        render 'new'
      end
    end

我刚刚开始使用RoR,因此无法理解这里的问题是什么。

2 个答案:

答案 0 :(得分:0)

显然你@article是零。如果您调用/访问user_id nil对象的@article,则会出现错误。

您需要确保首先定义def create @article = Article.new(article_params) @article.user_id = current_user.id if @article.save redirect_to @article else render 'new' end end private def article_params params.require(:article).permit(:title, :text) end ,类似这样

f

答案 1 :(得分:0)

您必须先创建Article的实例。然后为记录分配user_idsave

def create
  @article = Article.new
  @article.user_id = current_user.id

  @article.save
  if @article.errors.any?
    # error handling
  else
    render 'new'
  end
end