LoginSignup
0
0

More than 1 year has passed since last update.

accepts_nested_attributes_forを使ったデータ生成でハマった話

Last updated at Posted at 2022-06-26

どうもaono1234と申します。記事がいいなと思ったらtwitterのフォローもお待ちしております‼
https://twitter.com/takeshi_program

accepts_nested_attributes_for でデータ保存をする際、テーブル同士が1対1なのか1対多なのかで書き方が違うらしい

1対1の場合

params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
member = Member.create(params[:member])

createに渡すデータはハッシュを渡し、その中のavatar_attributesはハッシュのデータ。

1対多の場合

params = { member: {
  name: 'joe', posts_attributes: [
    { title: 'Kari, the awesome Ruby documentation browser!' },
    { title: 'The egalitarian assumption of the modern citizen' },
    { title: '', _destroy: '1' } # this will be ignored
  ]
}}

member = Member.create(params[:member])

createに渡すデータはハッシュを渡しその中のposts_attribuesは配列のデータ。

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