This project is archived and is in readonly mode.

#6461 new
Aaron Gough

find_or_create_by behaves incorrectly when used with multiple attributes through has_many association

Reported by Aaron Gough | February 22nd, 2011 @ 06:33 PM

When using a find_or_create_by method with multiple attributes through an association, the hash of attributes is incorrectly assigned to the attribute you are finding on:

ParentModel.first.child_models.find_or_create_by_attribute_1(:attribute_1 => "test1", :attribute_2 => "test2")

#=> #<ChildModel id: 1, attribute_1: {:attribute_1=>"test1", :attribute_2=>"test2"}, attribute_2: nil, parent_model_id: 1, created_at: "2011-02-22 17:54:33", updated_at: "2011-02-22 17:54:33">

The same find_or_create_by method works correctly when not going through the association:

ChildModel.find_or_create_by_attribute_1(:attribute_1 => "test3", :attribute_2 => "test5")

#=> #<ChildModel id: 2, attribute_1: "test3", attribute_2: "test5", parent_model_id: nil, created_at: "2011-02-22 17:57:36", updated_at: "2011-02-22 17:57:36">

Steps to reproduce:

> rails _2.3.11_ test
> cd test
> script/generate model ParentModel
> script/generate model ChildModel attribute_1:string attribute_2:string parent_model:references
> rake db:create
> rake db:migrate
# app/models/parent_model.rb
class ParentModel < ActiveRecord::Base
  has_many :child_models
end
# app/models/child_model.rb
class ChildModel < ActiveRecord::Base
  belongs_to :parent_model
end

Then run the following:

> script/console
ruby-1.8.7-p330> ParentModel.create
ruby-1.8.7-p330> ParentModel.first.child_models.find_or_create_by_attribute_1(:attribute_1 => "test1", :attribute_2 => "test2")

I have confirmed that this behaviour was not happening in Rails 2.3.4, but I haven't narrowed down the version more than that yet...

No comments found

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

Referenced by

Pages