autosave 関連元に対するsave実行時に関連先もsaveを実行する

使用可能な関連付け

  • belongs_to
  • has_and_belongs_to_many
  • has_many
  • has_one

対となる関連に指定するオプション

なし

概要

関連元のsave実行時に関連先に対してもsaveを実行する。mark_for_destructionメソッドによって削除マークがつけられている場合は削除を行う。

class Author < ApplicationRecord
  has_many :books, autosave: true
end

class Book < ApplicationRecord
  belongs_to :author
end

このような関連定義のとき、以下のような挙動になる。

author = Author.last
author.books[0].title = 'hoge'
author.save # => Bookに対するUPDATE文が実行される

autosaveオプションの指定がなければ、Bookに対するUPDATE文は発行されない。

新規レコードなら、autosaveオプションが未指定でも保存される。これは以下のような関連元が保存済みの場合も当てはまる。

class Author < ApplicationRecord
  has_many :books
end

author = Author.last
author.books.build
autho.save # => buildしたBookのINSERT文が実行される