William Weckl
William Weckl

Reputation: 2455

Rails 4 nested_attributes update

I'm getting an error when updating only the nested.

What I'm doing:

user = User.find(1)
user.update(data_attributes: {race: 2})

My models:

class User < ActiveRecord::Base
  has_one :data, inverse_of: :user, class_name: UserData, autosave: true
  accepts_nested_attributes_for :data
end

class UserData < ActiveRecord::Base
  self.table_name = 'user_data'
  belongs_to :user, inverse_of: :data
end

The error:

Mysql2::Error: Column 'user_id' cannot be null: UPDATE `user_data` SET `user_id` = NULL, `updated_at` = '2015-01-05 10:27:47.680681' WHERE `user_data`.`id` = 1

Upvotes: 4

Views: 165

Answers (2)

fjuan
fjuan

Reputation: 2324

If you want to update an existing data record, you have to include the object ID on the attributes_param:

user = User.find(1)
user_data_id = user.data.id
user.update(data_attributes: { id: user_data_id, race: '2' })

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76424

Your user_data table has a user_id column which is not nullable. When you try to update a record, but you are not setting the value of user_id, thus it is null. And, as mentioned above, the column is not nullable. You need to either set it to be nullable, or to set it to the correct value.

Upvotes: 0

Related Questions