Sean Magyar
Sean Magyar

Reputation: 2380

rails4 dependent destroy callback error

I have a role attribute on the ProductUser model. Users can be deleted by the owner (role), and I wanna make sure the owner can't delete himself while the product exists. However, when the product gets deleted all the product_users should be gone including the owner.

The following code throws an ActiveRecord::RecordNotDestroyed - Failed to destroy the record error when I try to delete the product. I guess this is because of the order of the execution due to the dependent: :destroy. How can I make this work?

class ProductUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :product, touch: true

  before_destroy :check_for_owner

  def check_for_owner
    if product && role == "owner" #If I use simply: if role == "owner", it still doesn't work.
      errors[:base] << "Owner can't be deleted!"
      return false
    end
  end
end


class Product < ActiveRecord::Base
  has_many :product_users, dependent: :destroy
  ....
end

Upvotes: 0

Views: 234

Answers (1)

j-dexx
j-dexx

Reputation: 10406

Have you considered simply not showing the delete button for the ProductUser record if the user is the owner?

In any case, if you use a foreign key rather than dependent destroy then the destroying will happen at the database level and the product user models won't be instantiated which would solve your issue.

So in a migration

def change
  add_foreign_key :product_users, :products, on_delete: :cascade
end

Then on product remove the dependent destroy option

class Product < ActiveRecord::Base
  has_many :product_users
end

With the on delete cascade option the database will destroy the product's product users when the product is deleted.

Upvotes: 2

Related Questions