Ruby on rails 如何为具有一个关系的模型强允许参数
我有以下联系 用户有一个配置文件 配置文件有许多图像 在创建用户时,我希望一次性更新配置文件和图像Ruby on rails 如何为具有一个关系的模型强允许参数,ruby-on-rails,Ruby On Rails,我有以下联系 用户有一个配置文件 配置文件有许多图像 在创建用户时,我希望一次性更新配置文件和图像 class User < ApplicationRecord has_one :profile accepts_nested_attributes_for :profile end class Profile < ApplicationRecord belongs_to :user has_many :images accepts_nested_attribute
class User < ApplicationRecord
has_one :profile
accepts_nested_attributes_for :profile
end
class Profile < ApplicationRecord
belongs_to :user
has_many :images
accepts_nested_attributes_for :images
end
class Image < ApplicationRecord
belongs_to :profile
end
输出是这样的
Started POST "/create_user" for 127.0.0.1 at 2017-05-04 18:55:01 +0530
ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by UsersController#create as */*
Parameters: {"user"=>{"name"=>"vamsi", "profile_attributes"=>{"address"=>"my home address", "images_attributes"=>{"0"=>{"image_url"=>"url1"}, "1"=>{"image_url"=>"url2"}}}}}
(0.1ms) begin transaction
(0.1ms) rollback transaction
下面是一个示例应用程序,它设置了上述关联
您能否通过调试
@user.errors.messages
{:“profile.user”=>[“必须存在”],:“profile.images.profile”=>[“必须存在”]}来检查错误是什么这就是我得到的感觉,问题是你在配置文件模型中的user\u id
和图像模型中的profile\u id
上有状态验证,但是rails在保存用户和配置文件模型之前尝试验证这些字段我没有任何类似的验证,无论我有什么代码,都是我在那里以及github repo中提到的
{
"user": {
"name": "vamsi",
"profile_attributes": {
"address": "my home address",
"images_attributes": {
"0": {
"image_url": "url1"
},
"1": {
"image_url": "url2"
}
}
}
}
}
Started POST "/create_user" for 127.0.0.1 at 2017-05-04 18:55:01 +0530
ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by UsersController#create as */*
Parameters: {"user"=>{"name"=>"vamsi", "profile_attributes"=>{"address"=>"my home address", "images_attributes"=>{"0"=>{"image_url"=>"url1"}, "1"=>{"image_url"=>"url2"}}}}}
(0.1ms) begin transaction
(0.1ms) rollback transaction