I'm building a RESTful API in Rails 4, and having a difficult time with getting Rails to send nested form attributes for a has_one association through to the database.
I believe that my models are set up as they should be:
class User < ActiveRecord::Base
has_one :address, dependent: :destroy
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
belongs_to :user
end
And in my controller, I have:
class API::V1::UsersController < API::V1::APIController
wrap_parameters format: [:json], include: [:email, :address]
def create
@user = User.create(user_params)
@user.build_address
if @user.save
render :json => @user
else
render :json => { :errors => @user.errors.full_messages }, :status => 422
end
end
private
def user_params
params.require(:user).permit(:email, :address_attributes => [:id, :line1, :line2, :city, :state, :zip])
end
end
When I post the following JSON object...
{
"email": "test@example.com",
"address": {
"line1": "123 Fake St",
"line2": "",
"city": "New York",
"state": "NY",
"zip": "10000"
}
}
...These parameters are being passed to the controller:
Parameters: {"email"=>"test@example.com", "address"=>{"line1"=>"123 Fake St", "line2"=>"", "city"=>"New York", "state"=>"NY", "zip"=>"10000"}, "user"=>{"email"=>"test@example.com", "address"=>{"line1"=>"123 Fake St", "line2"=>"", "city"=>"New York", "state"=>"NY", "zip"=>"10000"}}}
And yet, Rails only inserts the timestamps and user_id association into Postgres.
id | user_id | line1 | line2 | city | state | zip | created_at | updated_at
--------------------------------------+--------------------------------------+-------+-------+------+-------+-----+----------------------------+----------------------------
f09263ba-2046-446f-b0f3-3030bf3bc23e | 3025d5aa-ed3c-4fac-bae3-24deede59264 | | | | | | 2014-07-27 21:21:58.945165 | 2014-07-27 21:21:58.945165
Totally stumped---what am I missing?