Rails 4, basic JSON API - I am tying to update Status object with association Position objects.
Job Status model:
class JobStatus < ActiveRecord::Base
belongs_to :job
has_many :positions
accepts_nested_attributes_for :positions, limit: 1
validates :job_id,
:slug,
presence: true
end
Position Model:
class Position < ActiveRecord::Base
belongs_to :agent
belongs_to :job_status
validates :job_status_id,
:agent_id,
:lat,
:lng,
presence: true
end
Job Statuses Controller:
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
This is the JSON I am posting:
{
"slug":"started",
"notes":"this xyz notes",
"positions_attributes":[{
"lat" : "-72.348596",
"lng":"42.983456"
}]
}
When I do "logger.warn params" immediately above the @status.positions.build:
{"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"}}
And the error message that gets returned to me:
{
"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"
]
}
So I'm not really sure where my problem is - are my strong parameters not allowed correctly? Should I be posting an array of positions because it's a has_many relationship, even though I only want to create one at a time? Am I not using .build correctly? I've playing monkeying around with all of these, but not luck - I'm pretty sure there's something obvious I am just not seeing.
Also, if anyone has a way to log output the data from wherever the problem is coming from, that would be v. helpful in the future.