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 with decorated join model saves incorrectly

#1376

The attached patch is several failing tests that show a problem with using has_one :through with a decorated model.

Models are:


# simplified for readability - see full model in source
class Member < ActiveRecord::Base
  has_one :member_detail
  has_one :organization, :through => :member_detail
end

class MemberDetail < ActiveRecord::Base
  # has additional string field 'extra_data'
  belongs_to :member
  belongs_to :organization
end

class Organization < ActiveRecord::Base
  has_many :member_details
  has_many :members, :through => :member_details
end

The problem appears when you create a member, add a member_detail to it, and then add it to an organization. Either two MemberDetails get created, or one is created without the extra_data field set correctly.

See attached tests for more details - all three currently fail.

Reported by Matt Jones · November 14th, 2008 @ 06:18 PM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Matt Jones
    Matt Jones
    • Tag changed from 2.2.rc1, bug, edge, has_one_through to 2.2.rc1, bug, edge, has_one_through, patch

    Update: Some digging tracked this down to HasOneThroughAssociation#create_through_record; it was always deleting the join model record. The attached patch instead uses update_attributes if the join model already exists, and includes tests.

    Two of the tests in the previous patch were removed; adding records to the association from the other side doesn't work correctly. Thus

    
    @organization.members << @member
    

    will still yield bad behavior - but I'm not sure if it should work. The has_many :through on @organization doesn't know anything about the associations defined on @member. Maybe there needs to be a warning in the docs?

    November 15th, 2008 @ 07:16 AM

  2. Michael Koziarski
    Michael Koziarski
    • State changed from new to resolved

    Nice find,

    Yeah, the inverses of associations don't work anywhere in rails at present. The same is true with a simple has_many /belongs_to.

    Ideally we can fix that in 2.3, but depends on people getting the time and motivation

    Fixed for 2-2 and master.

    November 15th, 2008 @ 05:24 PM