2014-07-11 123 views
0

Rails 4,基本的JSON API - 我打算用關聯Position對象來更新Status對象。Rails 4,嵌套的屬性,強大的參數和JSON

工作狀態模式:

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嗎?我一直在玩弄所有這些,但不是運氣 - 我很確定有一些明顯的我只是沒有看到。另外,如果有人有辦法記錄輸出的問題來自哪裏的數據,那麼這對未來會有幫助。

回答

1

你的問題是這樣的一行:

@status.positions.build 

這僅需要在new方法來建立HTML表單,這顯然是不適用於這種情況。這種方法實際上消除了您發佈的所有position參數。

刪除此行將解決您的問題。

+0

完美工作。謝謝! – crypticsymbols