Patricio S
Patricio S

Reputation: 2130

How to use the callback after_destroy (or something similar) in Rails 4?

I'm creating an application that creates polls, each poll has many poll pages, and each poll page has many question clusters, what I want to do is that when a question cluster is deleted, search every question clusters from the same page that had a higher position, and diminish 1.

This is what I tried, but it doesn't even runs:

after_destroy :reassign_position

private

def reassign_position
  question_clusters = QuestionCluster.where(poll_page_id: self.poll_page_id)
  question_clusters.where("position > ?", self.position)

  quest_cluster.each do |question_cluster|
    question_cluster.position -= 1
  end
end

How can I accomplish what I want?

Upvotes: 1

Views: 1069

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

You are not updating the question_cluster's attribute (position). Take a look:

def reassign_position
  question_clusters = QuestionCluster.where(poll_page_id: self.poll_page_id)
  question_clusters.where("position > ?", self.position)

  quest_cluster.each do |question_cluster|
    # actually update the question_cluster
    question_cluster.update!(position: question_cluster.position - 1) # <========
  end
end

Upvotes: 1

Related Questions