我的模型架构:
轮询
has_many :questions
has_many :responses :through => :questions
问题
belongs_to :poll
has_many :responses
回复
belongs_to :question
问题当我尝试运行@poll.responses.delete_all
或clear
或destroy_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)
答案 0 :(得分:3)
尝试
Poll.first.responses.each(&:destroy)
删除仅在联接模型上的关联为:belongs_to
时有效。
答案 1 :(得分:0)
你需要使用destroy_all,它最适合关系。
@poll.responses.destroy_all