gpt4 book ai didi

ruby-on-rails - 如何在需要 = true 时建立和保存父子记录?

转载 作者:行者123 更新时间:2023-12-04 07:37:43 28 4
gpt4 key购买 nike

鉴于以下模型

class Parent
has_many :children
end
class Child
belongs_to :parent, required: true
end

是否可以同时创建 Parent 和 Children?
@parent = Parent.new(valid_attributes)
@parent.children.build(valid_attributes)
@parent.save
@parent.errors.messages
#=> {:"children.parent"=>["must exist"]}

删除 required: true允许保存记录。但是有没有办法让 parent 和 child 一起被保存,同时仍然验证 parent 的存在?

最佳答案

您可以使用 accepts_nested_attributes_for , 在关联上启用嵌套属性允许您一次性创建父子项。

型号 parent.rb

class Parent < ActiveRecord::Base
has_many :children

#enable nested attributes
accepts_nested_attributes_for :children
end

型号 child.rb
class Child < ActiveRecord::Base
belongs_to :parent
end

构建并保存您的对象 parent_controller.rb
class ParentsController < ApplicationController

def new
@parent = Parent.new
@parent.children.build

respond_to do |format|
format.html # new.html.erb
format.json { render json: @parent }
end
end

def create
#your params should look like.
params = {
parent: {
name: 'dummy parent',
children_attributes: [
{ title: 'dummy child 1' },
{ title: 'dummy child 2' }
]
}
}

#You can save your object at once.
@parent = Parent.create(params[:parent])

#Or you can set object attributes manually and then save it.
@parent.name = params[:parent][:name]
@parent.children_attributes = params[:parent][:children_attributes]
@parent.save
end

end

For more info: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

关于ruby-on-rails - 如何在需要 = true 时建立和保存父子记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966403/

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