Orderモデルが複数のItem持っている状況を考えます。
Orderモデルにaccepts_nested_attributes_for
を追加します。
こうすることでOrderモデルはitems_attributes
属性を受け入れるようになります。
order.rb
class Order < ApplicationRecord
has_many :items
+ accepts_nested_attributes_for :items
end
実際に同時作成するときにはitems_attributes
で子モデル属性の配列を渡せば良いです。
orders_controller.rb
order = Order.new(
customer: "田中",
items_attributes: [
{ name: "商品A", price: 1000 },
{ name: "商品B", price: 2000 }
]
)
order.save
このときに、関連モデルのバリデーションも実行されます。
ただし、子モデルにおけるバリデーションエラーは親モデルには伝播しません。