yuletide
yuletide

Reputation: 134

Deleting records via rails has_many :through

My model schema:

Poll

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

Question

belongs_to :poll
has_many :responses

Response

belongs_to :question

Problem when I try to run @poll.responses.delete_all or clear or destroy_all I get this error:

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

Update: Still not sure why this is happening, but here's a workaround: @poll.responses.each(&:destroy)

Upvotes: 2

Views: 928

Answers (2)

Serena
Serena

Reputation: 154

Try

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

Delete only works when the association on the join model is :belongs_to.

Upvotes: 3

Joel Friedlaender
Joel Friedlaender

Reputation: 2191

You need to use destroy_all, it will work best with relations.

@poll.responses.destroy_all

Upvotes: 0

Related Questions