2012-08-10 89 views
2

我的模型架构:通过导轨的has_many删除记录:通过

投票

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)

回答

3

尝试

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

删除,只有当在连接模型的关联:belongs_to工作。

+0

这工程!留下它打开一下,看看是否有人可以解释奇怪的错误。 – yuletide 2012-08-10 00:32:05

+0

错误是说你不能通过Poll直接修改Poll#记录集合,因为问题:has_many:polls。该集合是只读的。 – Serena 2012-08-10 00:42:16

+0

但问题belongs_to民意调查,而不是问题:has_many:民意调查 – yuletide 2012-08-10 01:07:28

0

您需要使用destroy_all,它将与关系最好地发挥作用。

@poll.responses.destroy_all 
+1

我得到同样的错误...还有文档建议使用删除时,有很多项目,以避免触发验证/回调 – yuletide 2012-08-10 00:21:31