Zabba
Zabba

Reputation: 65517

Associations not loaded in before_destroy callback

I have a simple User & Account model. I want to prevent deletion of an account if it has users attached to it. I create one User and one Account and associate them. Then, I do Account.find(x).destroy at the console. The account gets destroyed!

Notes:

  1. User's account_id is correct.
  2. Account.find(x).users.empty? at console returns false
  3. Account.find(x).destroyable? at console returns true
  4. users.empty? in def destroyable? returns true !!

I'm doing something wrong? What is it?

Code (Rails 3.2.9 on Ruby 1.9.2-p290):

class User < ActiveRecord::Base
  belongs_to :account
end

class Account < ActiveRecord::Base

  has_many :users, dependent: :destroy
  attr_accessible :name
  before_destroy :destroyable?

  def destroyable?
    if users.empty? # This returns true when called via callback.
      true
    else
      false
    end
  end

end

Upvotes: 3

Views: 993

Answers (2)

Zabba
Zabba

Reputation: 65517

So, turns out this is yet another Rails pitfall.

Solution is to move the before_destroy above the has_many call.

@Yves Senn, you are right. I will avoid it from now on. Using dependent: :restrict instead of dependent :destroy, which in this case, eliminates the need for my before_destroy callback.

Upvotes: 7

Yves Senn
Yves Senn

Reputation: 1996

I think the problem is dependent: :destroy. If you don't want to destroy accounts with associated users, you should not add the dependent option.

Also this is very risky, since it could accidentally destroy users.

Upvotes: 2

Related Questions