This project is archived and is in readonly mode.

#1376 ✓resolved
Matt Jones

has_one :through with decorated join model saves incorrectly

Reported by Matt Jones | November 14th, 2008 @ 06:18 PM | in 2.x

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.

Comments and changes to this ticket

  • Matt Jones

    Matt Jones November 15th, 2008 @ 07:16 AM

    • 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?

  • Michael Koziarski

    Michael Koziarski November 15th, 2008 @ 05:24 PM

    • 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.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages