Railsのhas_oneのsaveに注意!
has_one(1:1)のアソシエーションの場合
autosave: true
を付けないと、アソシエーション先authorのnameを変更してpostをsaveしても、authorはsaveされない
class Post has_one :author, autosave: true end
post = Post.find(1) post.title # => "The current global position of migrating ducks" post.author.name # => "alloy" post.title = "On the migration of ducks" post.author.name = "Eloy Duran" post.save post.reload post.title # => "On the migration of ducks" post.author.name # => "Eloy Duran”
has_many(1:N)のリレーションの場合
- autosaveオプションは、不要
- postをsaveすると、commentsもsaveされる
class Post has_many :comments # :autosave option is not declared end post = Post.new(title: 'ruby rocks') post.comments.build(body: 'hello world') post.save # => saves both post and comment post = Post.create(title: 'ruby rocks') post.comments.build(body: 'hello world') post.save # => saves both post and comment post = Post.create(title: 'ruby rocks') post.comments.create(body: 'hello world') post.save # => saves both post and comment