2010-10-09 59 views
1

我有一篇文章has_many評論。軌道原子刪除

當我創建評論時,我可以使用「新建」將它們構建在內存中,並且評論記錄僅在文章保存時才創建。

這樣的機制是否存在標記刪除註釋,以便他們的記錄只在保存文章時被刪除?

謝謝。

回答

3

我建議你熟悉#accepts_nested_attributes_for。這個例子基本上是你想要的。這是一個改寫的:

class Post < ActiveRecord::Base 
    has_many :comments 
    accepts_nested_attributes_for :comments, :allow_destroy => true 
end 

post = Post.find(1) # With 3 comments 
post.comments_attributes = [{:_destroy => "1", :id => post.comments.first.id}] 
# Look ma! No SQL statements! 
post.save! 
# BEGIN/UPDATE posts/DELETE FROM comments WHERE id = X/COMMIT 
1

做一個交易:

Article.transaction do 
    ... 
end