accepts_nested_attributes_forに指定したアソシエーションは親が更新されると子も更新してくれる
accepts_nested_attributes_forってフォームから親子まとめて保存する時に使うものと思ってましたが、フォームを使わなくても親子をまとめて保存してくれるんですね。知らなかった、何て便利なのでしょう。
# ex class Diary < ActiveRecord::Base has_many :comments accepts_nested_attributes_for :comments end diary = Diary.first # 変更前のコメントは以下だとします diary.comments.first.content #=> '変更前のコメント' # コメントを変更します diary.comments.first.content = '変更後のコメント' # この状態で親を保存します diary.touch # すると子も保存してくれる diary.comments.first.content #=> '変更後のコメント'
上記の後、調べたところ親子をまとめて保存する際にaccepts_nested_attributes_forを使わずに、もっと素直にできることがわかった。
どうするかというとアソシエーションの:autosaveオプションをtrueに設定する。
class Diary < ActiveRecord::Base has_many :comments, :autosave => true end