1

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?

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
Madalina
  • 457
  • 1
  • 5
  • 14
  • 1
    Just do `@user.reload`... after `@user.destroy`.. – Arup Rakshit May 25 '15 at 11:33
  • If I write that right after @user.destroy it gives me one error that says it couldn't find the User with id='12'. By the way, the associated object is not being destroyed in development too. I think the problem is with the models – Madalina May 25 '15 at 11:38

1 Answers1

0

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
Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
  • I suppose that you wanted to write `UserDetail.find_by(:user_id => @user.id)`. If so, I don't understand how it is supposed to work? Shouldn't @user.id be nil? – Madalina May 26 '15 at 10:13
  • Oh good catch, yeah, it should be `@user.id`. But it's not nil, 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``` – Waynn Lue May 26 '15 at 16:23