そういうことだったんですね

いろいろ調べたり学んだりしたことを忘れないように書き連ねています

Rails - 入れ子構造のモデルを更新する(2)

accepts_nested_attributes_for の続きです。

子要素となるテーブルは新規追加?or更新?

:id で挙動がかわります。

子要素の :id パラメータを指定すると更新(UPDATE)、指定しない場合は挿入(INSERT)となります。

例)Blog - Author のようなモデルがあった場合

app/models/blog.rb

class Blog < ActiveRecord::Base
  has_many authors
  accepts_nested_attributes_for :author
end

app/models/author.rb

class Author < ActiveRecord::Base
  belongs_to blog
end

 

新規登録する場合はこんな同じ

  blog = Blog.create :title=>"foo", :author_attributes=>{ :name=>"Boo" }
  blog.authors.first              => #<Author id=2 name="Boo">

既存のレコードを変更する場合

  blog = Blog.find(1)
  blog.update( :author_attributes=>{:id => 2, :name=>"Bar"}
  blog.authors.first              => #<Author id=2 name="Bar">

メタプログラミングRuby

メタプログラミングRuby