gpt4 book ai didi

ruby-on-rails - Rails 4 嵌套属性更新

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:42 24 4
gpt4 key购买 nike

仅更新嵌套时出现错误。

我在做什么:

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

我的模型:

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

错误:

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

最佳答案

如果您想更新现有的data 记录,您必须在attributes_param 中包含对象ID:

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

关于ruby-on-rails - Rails 4 嵌套属性更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27777879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com