我一直在检查belongs_to方法的选项并测试 Rails 3.2.7 中的以下行为
根据上面的链接,该:dependent
选项指出
如果设置为 :destroy,则关联对象在该对象被销毁时被销毁。如果设置为 :delete,则删除关联对象而不调用其 destroy 方法。
据我了解,如果在以下情况下删除帖子,则应删除作者:
class Post < ActiveRecord::Base
belongs_to :author, :dependent => :delete
end
class Author < ActiveRecord::Base
attr_accessible :name
has_one :post
before_destroy :log_author_removal
private
def log_author_removal
logger.error('Author is getting removed')
end
end
在控制台中:
> Post.first
Post Load (0.4ms) SELECT "posts".* FROM "posts" LIMIT 1
=> #<Post id: 5, title: "Post 5", author_id: 3>
> p.delete
SQL (197.7ms) DELETE FROM "posts" WHERE "posts"."id" = 5
=> #<Post id: 5, title: "Post 5", author_id: 3>
> Author.find(3)
Author Load (0.5ms) SELECT "authors".* FROM "authors" WHERE "authors"."id" = ? LIMIT 1 [["id", 3]]
=> #<Author id: 3, name: "Author 3">
但是调用p.destroy
会删除关联作者。
我是否误解了上面引用的陈述?