Given the following models
class Parent
has_many :children
end
class Child
belongs_to :parent, required: true
end
Is it possible to create Parent and Children at the same time?
@parent = Parent.new(valid_attributes)
@parent.children.build(valid_attributes)
@parent.save
@parent.errors.messages
#=> {:"children.parent"=>["must exist"]}
Removing the required: true
allows the record to save. But is there a way to enable parents and children to be saved together while still validating parent exists?
You can use accepts_nested_attributes_for
, Enabling nested attributes on association allows you to create the parent and child in one go.
Model parent.rb
class Parent < ActiveRecord::Base
has_many :children
#enable nested attributes
accepts_nested_attributes_for :children
end
Model child.rb
class Child < ActiveRecord::Base
belongs_to :parent
end
Build and save your object parents_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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.