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.

uniq bug on array of ActiveRecord Objects

#2960

The uniq method on collections of ActiveRecord Objects relies on the primary_key of the model to determine if two objects are the same.

This can lead to problems if the table does not have an 'id' column, and set_primary_key is not defined, or if the table uses a composite key.

This really boils down to a problem with ==, but manifests in [].uniq

For example,
If you have a table "items" without a column 'id'

  Item.create(:some_id => 1, :name => "Item 1")
  Item.create(:some_id => 2, :name => "Item 2")

  a = Item.find_by_some_id(1)
  b = Item.find_by_some_id(2)
  a == b #=> true, expected FALSE

In most cases, it is a simple case of utilizing 'set_primary_key', however, when one is interfacing with legacy databases with composite keys? It is also unexpected behavior. There is nothing similar between the two objects besides that they are the same class.

I'm not sure what the proper solution would be. If the primary_key doesn't match any columns, compare values of the attributes? I'll leave that up to debate.

Demo Attached, just rake db:migrate

Reported by Peter Leonhardt · July 27th, 2009 @ 09:41 PM

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

Activity

  1. Michael Koziarski
    Michael Koziarski
    • Tag changed from active_record, array to active_record, array, bugmash

    August 3rd, 2009 @ 06:02 AM

  2. Cristi Balan
    Cristi Balan

    -1

    Since composite keys are not part of AR core, but added through plugins, I think the equality of records should be handled in the same plugin as well by overriding ==.

    August 8th, 2009 @ 12:08 PM

  3. John Pignata
    John Pignata

    -1

    Where composite keys or Rails-known primary keys aren't used, == should be overriden.

    August 9th, 2009 @ 05:58 AM

  4. Kieran P
    Kieran P

    -1 In agreement with Cristi and Johns comments. If you're needing this, overwrite the functionality in your own code since its a limited case.

    August 9th, 2009 @ 06:22 AM

  5. Rizwan Reza
    Rizwan Reza

    not reproducible

    -1 Agreed with Cristi... it's a job of a plugin.

    August 9th, 2009 @ 11:24 PM

  6. Jeremy Kemper
    Jeremy Kemper
    • State changed from new to wontfix
    • Tag changed from active_record, array, bugmash to active_record, array
    • Milestone cleared.

    August 9th, 2009 @ 11:26 PM