Rails 4 update nested_attributes

I get an error when updating only nested.

What am I 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

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
+4
source share
2 answers

If you want to update an existing record data, you must include the object identifier in the param attributes:

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

user_data table user_id column, NULL. update , user_id, , null. , , column . NULL, .

0

Source: https://habr.com/ru/post/1569974/


All Articles