Question

I have a model User.rb that accepts_nested_attributes_for :address

user.rb

has_one :address
accepts_nested_attributes_for :address

address.rb

belongs_to :user

When I try to test it using Rails console the following happens

user = User.find(157)

User Load (1.5ms) SELECT "users". FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 157]]*

#<User id: 157, name: "John Doe", email: ...

user.address.phone

UserAddress Load (0.8ms) SELECT "addresses". FROM "addresses" WHERE "addresses"."type" IN ('UserAddress') AND "addresses"."user_id" = $1 ORDER BY "addresses"."id" ASC LIMIT 1 [["user_id", 157]]

"1234567"

That's fine so far. However, the following does not work:

user.update(:address_attributes => {:phone  => "888888"})

It throws

ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR:  null value in column "user_id" violates not-null constraint

The SQL doesn't make much sense to me

UPDATE "addresses" SET "user_id" = $1, "updated_at" = $2 WHERE "addresses"."type" IN ('UserAddress') AND "addresses"."id" = 128  [["user_id", nil], ["updated_at", Sun, 02 Feb 2014 19:55:07 CET +01:00]]

Why does it try to update user_id with nil when I actually updated the phone attribute?

Was it helpful?

Solution

Perhaps the issue is that you're not using the correct ActiveRecord object?

Maybe you could try:

user.address.update_attributes({phone: "888888"})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top