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