Foreign key preventing me from destroying records

Hi, I’ve got a feedback and comments model, with references between them. But, when I attempt to destroy an individual comment or feedback, I get ERROR: update or delete on table … violates foreign key constraint.

I may have missed something in my models or what can I do to fix these 2 issues.

Have you set up dependent: [:destroy, :nullify, some other option] in your associations? If not, you will get this error, since you are trying to override a database constraint. It would be helpful if you posted just the relevant parts of your model code here, so we can suggest a solution. Like this:

  has_many :model_twos

  belongs_to :model_one


class Feedback2 < ActiveRecord::Base belongs_to :user has_many :feedback2comment end


class Feedback2comment < ActiveRecord::Base belongs_to :feedback2 belongs_to :user

belongs_to :parent, class_name: “Feedback2comment”, optional: true

belongs_to :parent, class_name: “Feedback2comment” has_many :feedback2comments, foreign_key: :parent_id end

ok i added, dependent: :delete_all in my feedback model.

let me see how the comments work out now.

ok, the top level feedback is deleting the feedback and all the comments good.

But, the comments are deleting everything as well…

Reply | <%= link_to 'Destroy', @feedback2comment , method: :delete, data: { confirm: 'Are you sure?' } %>

It’s going to the right controller, and I do have a method for destroy. I’ll have to dig a bit deeper.

well, it’s not hitting the right controller destroy method. :frowning:

Try this setup, maybe:

  belongs_to :user 
  has_many :feedback2comments, dependent: :destroy

  belongs_to :feedback2
  belongs_to :user
  belongs_to :parent, class_name: "Feedback2comment", optional: true
  has_many :children, class_name: "Feedback2comment", foreign_key: :parent_id, dependent: :destroy