我使用的是Ruby on Rails。
我的模特就是这样。
Weblog模型
class Weblog < ActiveRecord::Base
attr_accessible :body
has_many :comments, :dependent => :destroy
accepts_nested_attributes_for :comments
end
评论模型
class Comment < ActiveRecord::Base
attr_accessible :comment
belongs_to :weblog
end
我的控制台日志在这里
$ attr = {}
$ attr["blog"] = {"body" => "test body", "comments_attributes" => {"0" => {"comment" => "comment1"}, "1" => {"comment" => "comment2"}}}
$ blog = Weblog.new(attr["blog"])
$ blog.save #=> comment data are saved with id 1 and 2 in comments table
$ attr["blog"] = {"body" => "update test body", "comments_attributes" => {"0" => {"comment" => "commentA", "id" => "1"}}} # I want to delete comment data whose id is 2 in comment table
$ blog2 = Weblog.first
$ blog2.update_attributes(attr["blog"]) #=> updates are correctly finished..
但是注释表中id为2的数据不会被删除。
如何通过更新博客表来删除评论表数据。
答案 0 :(得分:0)
您需要在allow_destroy => true
电话中添加accepts_nested_attributes_for
选项:
class Weblog < ActiveRecord::Base
attr_accessible :body
has_many :comments, :dependent => :destroy
accepts_nested_attributes_for :comments, allow_destroy: true
end
答案 1 :(得分:0)
在声明模型接受嵌套属性时,您需要使用:allow_destroy选项。执行此操作后,如果要删除嵌套模型,则需要传递模型的id和值为“1”的特殊属性_destroy
您可以在http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
查看文档和示例