同时保存,错误处理

Save at same time, error handeling

假设我有这个简单的联想:

class Post < ActiveRecord::Base
  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 无效会发生什么,是否仍会创建评论?

如果附加的 comment 无效会发生什么,它是否仍然创建 post?

我希望当 commentpost 无效时,它不会保存任何内容。我做对了吗?

我需要 validates_associated 吗?谢谢

如果post无效,则不会保存相关记录。根据 Active Record Autosave Association 上的文档:

Saving of the parent, its associations, and the destruction of marked associations, all happen inside a transaction. This should never leave the database in an inconsistent state.

如果还必须验证子记录,则确实需要 validates_associated。但是请注意仅在关联的一侧调用 validates_associated,否则会创建循环引用。