【问题标题】:Rails4 NoMethodError (undefined method `[]' for nil:NilClass):Rails4 NoMethodError(nil:NilClass 的未定义方法“[]”):
【发布时间】:2014-05-09 13:03:41
【问题描述】:

您好,我在使用 Rails 4 时遇到以下错误。我的前端(EmberJs)提供了 json。

在 2014-03-30 00:54:18 -0400 开始为 127.0.0.1 发布“/articles” ArticlesController#create as JSON 处理 参数:{"article"=>{"title"=>"Title", "body"=>"Content", "author_id"=>"2", "author"=>nil}} 不允许的参数:作者 在 4782 毫秒内完成 500 个

NoMethodError (未定义方法[]' for nil:NilClass): app/controllers/articles_controller.rb:43:inblock in create' app/controllers/articles_controller.rb:42:in `create'

我的模型如下所示:

class Article < ActiveRecord::Base
 validates :title, presence: true
 validates :body, presence: true

 attr_accessible :title, :body, :author_id

 belongs_to :author
end

我的控制器如下所示:

class ArticlesController < ApplicationController
    def new
      @article = Article.new
      respond_to do |format|
       format.json { render json: @article }
      end
    end

   def create
    @article = Article.new(article_params)

    respond_to do |format|
      if @article.save
        format.json { render json: @article, status: :created, location: @article }
      else
        format.json { render json: @article, status: :unprocessable_entity }
      end
    end
  end

  private
  def article_params
    params.require(:article).permit(:title, :body, :author_id)
  end
end

【问题讨论】:

  • 您的文章控制器中的第 43 行是什么?您发布的那个甚至没有 43 行。另外,为什么在模型中使用 attr_accessible,而在控制器中使用强参数?
  • 我试图用 attr_accesible 解决问题,但它不起作用。第 43 行(它是控制器的摘录)对应于强参数 @article = Article.new(article_params) 的调用。我不明白的是为什么以及何时尝试访问数组并得到未定义的方法[]'错误。

标签: json ember.js ruby-on-rails-4 ember-data


【解决方案1】:

通过删除解决 gem 'protected_attributes' 来自 gemfile。

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 2013-01-14
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多