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?

More than 3 years have passed since last update.

accepts_nested_attributes_forで関連モデルの更新をする方法

Posted at

やりたいこと

accepts_nested_attributes_forを使い関連モデルの作成、更新も同時にやっている。

作成のタイミングで関連モデルだけは更新したいケースがあった。

やりかた

https://github.com/rails/rails/issues/7256#issuecomment-93172189
を自分用にかみ砕いてメモしたものです。

Foo (既存の更新) -> Bar (作成) -> Baz (既存の更新)
・Fooは更新
・Barは作成
・Bazは更新
をしたい。

その場合は以下のようにparamsを渡すだけでよい。

{
  foo: {
    id: "foo_id", => fooを更新するにはidを渡す
    ...
    bar_attributes: {
      ...
      baz_id: "baz_id", => bazを更新するにはbaz_idと
      baz_attributes: {
        id: "baz_id",  => idを渡す。
        ...
      }
    }
}
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?