Search code examples
ruby-on-railshas-onedependent-destroy

:dependent => :destroy doesn't work on has_one relation


In my models

class User < ActiveRecord::Base
    has_one :user_detail, dependent: :destroy
end

and

class UserDetail < ActiveRecord::Base
  belongs_to :user
end

When I call destroy for an User object, the associated UserDetail object is not being destroyed.

Here's a test (of course, it fails because user_detail is not nil):

  test "associate object should be destroyed" do
    user_id = @user.id
    @user.destroy
    user_detail = UserDetail.find_by(:user_id => user_id)
    assert_nil user_detail
  end

Does anyone have any idea why this happens?


Solution

  • Your logic is fine, but it's your test code that's the problem. Try this:

    test "associate object should be destroyed" do
      user_detail = @user.user_detail
      @user.destroy
      expect(UserDetail.find_by(:user_id => @user.id)).to be_nil
    end
    

    What's happening is the database row that corresponds to user_detail is being destroyed, but the variable still holds the value.

    edit to respond to comment since I can't put the code block in the comment:

    @user.id isn't nil because, if you test it, you'll see that the id is still preserved because it's the in memory model. I have a random rails app I'm testing, here's some console output:

    irb(main):002:0> l = Loan.first
    irb(main):003:0> l.destroy
    irb(main):004:0> l.id
    => 14