【问题标题】:Rails JSON Nested AttributesRails JSON 嵌套属性
【发布时间】:2013-07-28 18:17:41
【问题描述】:

我正在开发一个 Rails 4 API,客户端可以将数据发布到控制器,并将其保存在数据库中。我想知道如何实现用户发布嵌套 JSON,然后让控制器接受属性并使用它们创建模型。 JSON 看起来像

{
  'identifier': {
    'name': 'Test'
  }
}

然后我有一个私有方法

def parameters
    params.respond_to?(:permit) ?
        params.require(:picture).permit(:identifier) :
        params[:picture].slice(:identifier) rescue nil
  end

当我尝试以parameters[:identifier][:name] 访问控制器中的“名称”参数时,我得到未定义的方法 []。有什么建议吗?

创建动作

@picture = current_user.pictures.new(name: parameters[:identifier][:name])

图片模型只有t.string :name

【问题讨论】:

  • 发布您的控制器的创建操作代码以及您在数据库中的哪些字段,即您的模型

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


【解决方案1】:

看起来 JSON 将字符串 'identifier' 作为键,而您尝试使用符号 :identifier 访问它,该符号返回 nil。所以[] 没有在nil 上定义。你可能应该这样做parameters["identifier"]["name"]

【讨论】:

    【解决方案2】:

    您可以使用嵌套的 JSON,只要您在允许的参数中创建它们,例如:

      def parameters
        params.respond_to?(:permit) ?
            params.require(:picture).permit(:identifier => [ :name ]) :
            params[:picture].slice(:identifier => [ :name ]) rescue nil
      end
    

    这适用于使用强参数的 Rails 4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多