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.

find_or_create_by behaves incorrectly when used with multiple attributes through has_many association

#6461

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...

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

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

Activity

No comments yet.