This project is archived and is in readonly mode.

#6535 new
Casey Dreier

find_or_create_by on an association always creates new records

Reported by Casey Dreier | March 5th, 2011 @ 09:23 PM

Calling a dynamic find_or_create_by_ method on an association always ends up creating a new record because it improperly queries the database when attempting to find the record with the given values.

Attached is a test on a has_many association demonstrating this problem, as well as a simple patch that fixes it (spoiler: the finder arguments were passed incorrectly from a recent patch on this method).

Comments and changes to this ticket

  • Casey Dreier

    Casey Dreier March 5th, 2011 @ 09:28 PM

    Just to be clear, this bug report and patch are for Rails 2.3.11.

  • Jon Jensen

    Jon Jensen March 22nd, 2011 @ 07:44 PM

    In addition to the incorrect behavior, it can also cause unhandled exceptions for postgres. For example, company.employees.find_or_create_by_group_id_and_name(1, 'bob') would generate some SQL like "... group_id IN (1, 'bob') AND name IS NULL". In postgres you get an error, since 'bob' hasn't been explicitly cast to an integer.

  • Leon Miller-Out

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>

Attachments

Pages