2012-08-10 86 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