Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

has_one :through a belongs_to association will return nil on deleted records

#6037

This worked in rails 3.0.1 and now fails in rails 3.0.3 and in master. When a record is destroyed, attempting to load a has_one :through association on it will returning nil.

Here is an example test case

class MemberType < ActiveRecord::Base
end
class Member < ActiveRecord::Base
  belongs_to :member_type
  has_many :member_detail
end
class MemberDetail < ActiveRecord::Base
  belongs_to :member
  has_one :member_type, :through => :member
end
assert_not_nil @member_detail.member_type(true)        # => #<MemberDetail ...
@member_detail.destroy
assert_not_nil @member_detail.member.member_type(true) # => #<MemberDetail ...
assert_not_nil @member_detail.member_type(true)        # => nil

The issue is that AssociationProxy#load_target won't call find_target since @owner.persisted? and foreign_key_present are false.

Reported by John Hawthorn · November 22nd, 2010 @ 07:37 PM

State: resolved
Milestone: 3.0.5
Assigned to: Aaron Patterson Aaron Patterson
Importance: Low

Activity

  1. John Hawthorn
    John Hawthorn

    Here is my attempt at a patch

    It adds foreign_key_present to HasOneThroughAssociation which returns true when the through_reflection is a belongs_to and primary_key is not nil. Also adds test cases.

    November 22nd, 2010 @ 10:35 PM

  2. John Hawthorn
    John Hawthorn

    It seems that the commit which caused this issue (https://github.com/rails/rails/commit/f1c13b0dd7b22b5f6289ca1a09f1d...) has been reverted (https://github.com/rails/rails/commit/e444439fe28f873c783a4b99b1c9f....

    I've attached a new patch which contains only the test case.

    November 29th, 2010 @ 04:13 AM

  3. Aaron Patterson
    Aaron Patterson
    • State changed from new to open
    • Milestone cleared.
    • Assigned user set to Aaron Patterson
    • Importance changed from to Low

    November 29th, 2010 @ 05:00 AM

  4. Repository
  5. Repository
  6. Santiago Pastorino