Dynamic find_or_create_by_x_and_y always creates new records in Rails 2.3.11 #331

wants to merge 1 commit into


None yet
2 participants

daphonz commented Apr 28, 2011

This is a regression that was introduced in fdfc8e3.

Any create_or_find_by_x_and_y call on an association will aways create a new record.

To recreate:

Say you have two models, one has_many of another:

class Author < ActiveRecord::Base
  has_many :posts

class Post < ActiveRecord::Base
  belongs_to :author

Jump into the console and enable AR logging. Then run the dynamic find_or_create_by twice:

Author.first.posts.find_or_create_by_title_and_published('Post Title', true)
Author.first.posts.find_or_create_by_title_and_published('Post Title', true)

You'll see that the query looks generates something like

select * from posts where title IN ('Post Title', 1) and published = '' and author_id = 7

i.e. the title is getting passed an array of the input.

Failing test and patch included below in the merge request (9f7ff62).

Fixing dynamic finders on associations to properly send arguments to …
…the find_by_* method. Closes issue #330.

Commit fdfc8e3 introduced a bugfix to prevent additional values passed
to a dynamic find_or_create_by_x methods from confusing the finder.
This patch also broke the essential behavior of this method on an
association by incorrectly sending arguments to the find_by_x methods.
The finder method would always see its inputs as a single array of
values instead of individual arguments, almost guaranteeing that the
finder call would be incorrect, and that we'd always create a new
record instead.

This patch adds a splat operator to the parameter array we send along to
the dynamic finder so that it receives its inputs correctly, and
includes an additional test to ensure that repeated calls to
find_or_create_by_x only creates one new record.

josevalim commented Apr 28, 2011


@josevalim josevalim closed this Apr 28, 2011

cch1 pushed a commit to cch1/rails that referenced this pull request May 3, 2011

Merged pull request #331 from daphonz/2-3-stable.
Dynamic find_or_create_by_x_and_y always creates new records in Rails 2.3.11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment