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.

Assigning to has_many :through using the generated *_ids method does not insert in the same order

#3491

Suppose you have:

class Post
  has_many :readers
  has_many :people, :through => :readers
end

The following assignment will insert in the expected order:

@post.people = [@person1, @person2, @person3]

However this assignment will insert in an arbitrary order:

@post.person_ids = [@person1.id, @person2.id, @person3.id]

The fix for this looks a little ugly, but it performs well... we just create a hash of all the fetched records by id, then map the original ids to their respective objects (an O(n) operation in other words).

Attached is failing test case (and confirmation of the original correct behavior for the first case) plus fix. Tested against mysql, postgres and sqlite.

Reported by Gabe da Silveira · November 17th, 2009 @ 05:52 PM

State: committed
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Repository
    Repository
    • State changed from new to committed

    (from [df0720b8b74bd6d41d25390d332000b882b711d9]) Insert generated association members in the same order they are specified when assigning to a has_many :through using the generated *_ids method

    [#3491 Assigning to has_many :through using the generated *_ids method does not inse... state:committed]

    Signed-off-by: Jeremy Kemper jeremy@bitsweat.net
    http://github.com/rails/rails/commit/df0720b8b74bd6d41d25390d332000...

    November 18th, 2009 @ 06:25 AM

  2. Repository
    Repository

    (from [ea290e77e6c50b13a0c9000eceaa5412de6918bc]) Insert generated association members in the same order they are specified when assigning to a has_many :through using the generated *_ids method

    [#3491 Assigning to has_many :through using the generated *_ids method does not inse... state:committed]

    Signed-off-by: Jeremy Kemper jeremy@bitsweat.net
    http://github.com/rails/rails/commit/ea290e77e6c50b13a0c9000eceaa54...

    November 18th, 2009 @ 06:25 AM