【问题标题】:Rails 4, nested attributes, strong parameters & JSONRails 4、嵌套属性、强参数和 JSON
【发布时间】:2014-07-11 13:36:58
【问题描述】:

Rails 4,基本 JSON API - 我正在尝试使用关联 Position 对象更新 Status 对象。

工作状态模型:

class JobStatus < ActiveRecord::Base

    belongs_to :job
    has_many :positions

    accepts_nested_attributes_for :positions, limit: 1

    validates :job_id,
                    :slug,
                    presence: true

end

职位模型:

class Position < ActiveRecord::Base
  belongs_to :agent
  belongs_to :job_status

  validates :job_status_id,
                    :agent_id,
                    :lat,
                    :lng,
                    presence: true

end

工作状态控制器:

class Api::V1::Jobs::JobStatusesController < ApplicationController

    wrap_parameters format: [:json]

    def create

        @status = JobStatus.new(status_params)

        @status.job_id = params[:job_id]

        @status.positions.build

        if @status.save
            render :json => {status: 'success', saved_status: @status}.to_json
        else
            render :json => {status: 'failure', errors: @status.errors}.to_json
        end

    end

    private

        def status_params
            params.permit(:job_id, :slug, :notes, :positions_attributes => [:lat, :lng, :job_status_id, :agent_id])
        end

end

这是我发布的 JSON:

{
  "slug":"started",
  "notes":"this xyz notes",
  "positions_attributes":[{
    "lat" : "-72.348596",
    "lng":"42.983456"
  }]
}

当我在 @status.positions.build 上方执行“logger.warn params”时:

{"slug"=>"started", "notes"=>"this xyz notes", "positions_attributes"=>[{"lat"=>"-72.348596", "lng"=>"42.983456"}], "action"=>"create", "controller"=>"api/v1/jobs/job_statuses", "job_id"=>"3", "job_status"=>{"slug"=>"started", "notes"=>"this xyz notes"}}

以及返回给我的错误消息:

{
"status":"failure",
"errors":{
"positions.job_status_id":[
"can't be blank"
],
"positions.agent_id":[
"can't be blank"
],
"positions.lat":[
"can't be blank"
],
"positions.lng":[
"can't be blank"
]
}

所以我不确定我的问题出在哪里 - 我的强参数是否不正确?我是否应该发布一系列职位,因为它是一个 has_many 关系,即使我一次只想创建一个?我没有正确使用 .build 吗?我一直在玩弄所有这些,但不是运气 - 我很确定有一些明显的东西我没有看到。

另外,如果有人有办法从问题所在的任何地方记录输出数据,那将来会很有帮助。

【问题讨论】:

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


    【解决方案1】:

    你的问题是这一行:

    @status.positions.build
    

    这仅在构建HTML表单的new方法中需要,显然不适用于这种情况。此方法实际上是清除您发布的所有 position 参数。

    删除此行将解决您的问题。

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多