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?
Pre-Existing parent and child recordsClick on the 'Parent Account' field and then type in name of the account record that will be the parent record. Then click save.
Click the 'Object' Picklist, then select the Account record that started your process and select a record related to the Account: Note: These records are radio buttons, and only one may be selected. To update child records, select the send option 'Select a record related to the Account'
Rails: When to use :inverse_of in has_many, has_one or belongs_to associations. When you have two models in a has_many , has_one or belongs_to association, the :inverse_of option in Rails tells ActiveRecord that they're two sides of the same association.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With