通过rails has_many:through删除记录

时间:2012-08-10 00:14:52

标签: ruby-on-rails ruby-on-rails-3 activerecord

我的模型架构:

轮询

has_many :questions
has_many :responses :through => :questions

问题

belongs_to :poll
has_many :responses

回复

belongs_to :question

问题当我尝试运行@poll.responses.delete_allcleardestroy_all时出现此错误:

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection: Cannot modify association 'Poll#responses' because the source reflection class 'Response' is associated to 'Question' via :has_many.

更新:仍然不确定为什么会这样,但这是一个解决方法: @poll.responses.each(&:destroy)

2 个答案:

答案 0 :(得分:3)

尝试

Poll.first.responses.each(&:destroy)

删除仅在联接模型上的关联为:belongs_to时有效。

答案 1 :(得分:0)

你需要使用destroy_all,它最适合关系。

@poll.responses.destroy_all