0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

accepts_nested_attributes_forで関連モデルを同時作成する

Posted at

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

このときに、関連モデルのバリデーションも実行されます。
ただし、子モデルにおけるバリデーションエラーは親モデルには伝播しません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?