gpt4 book ai didi

ruby-on-rails - 接受 mongoid 的嵌套属性约定

转载 作者:可可西里 更新时间:2023-11-01 09:56:01 26 4
gpt4 key购买 nike

我正在尝试使用 mongoid 创建具有嵌套属性的表单。我的模型具有以下代码:

def Company
field :name

has_many :users, autosave: true, dependent: :destroy
accepts_nested_attributes_for :users
end

def User
belongs_to :company
has_one :profile
end

def Profile
belongs_to :user
end

从表单返回的参数按以下顺序排列:

"company"=>
{"users_attributes"=>
{"0"=>
{"profile_attributes"=>
{"first_name"=>"123123abcd123", "last_name"=>"abcd123123123"},
"email"=>"abcd@abcd.com123123123",
"password"=>"123123123123",
"password_confirmation"=>"123123123123"}},
"name"=>"abcd123123123",
"subdomain"=>"abcd123123123"}

调用 Company.create(params[:company]) 似乎有效,但它没有正确创建用户对象。当我执行 company.users 时,我可以看到该对象,但是当我执行 User.find 时,该文档不可用。阅读文档我意识到参数应该以下列方式传递:

"company"=>
{"users_attributes"=>
[{"profile_attributes"=>
{"first_name"=>"123123123", "last_name"=>"123123123"},
"email"=>"testin321@gmail.com",
"password"=>"123123",
"password_confirmation"=>"123123"}],
"name"=>"abcd123123123",
"subdomain"=>"abcd123123123"}

请注意为 users_attributes 使用数组而不是散列的细微差别。这工作正常,但它似乎并不像 Active Record 那样开箱即用(以及它应该如何像在 rails 中那样)。我不想获取参数散列并修改数据以使其遵循某些约定。有没有更好的方法,我是否遗漏了什么?

最佳答案

如果您可以将 inputs 命名为 user_attributes[],这将构成数组。

所以不用user_attributes[0][profile_attributes](我想你有这样的东西)

使其具有user_attributes[][profile_attributes]

关于ruby-on-rails - 接受 mongoid 的嵌套属性约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10387755/

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