diff --git a/lib/cocoon/view_helpers.rb b/lib/cocoon/view_helpers.rb index f01b6ba..3e7a6cf 100644 --- a/lib/cocoon/view_helpers.rb +++ b/lib/cocoon/view_helpers.rb @@ -84,9 +84,13 @@ module Cocoon # will create new Comment with author "Admin" def create_object(f, association) - assoc = f.object.class.reflect_on_association(association) - conditions = assoc.respond_to?(:conditions) ? assoc.conditions.flatten : [] - new_object = assoc.klass.new(*conditions) + assoc = f.object.class.reflect_on_association(association) + + if assoc.collection? + f.object.send(association).build + else + f.object.send("build_#{association}") + end end def get_partial_path(partial, association) diff --git a/spec/cocoon_spec.rb b/spec/cocoon_spec.rb index 865f68f..b1a4b1e 100644 --- a/spec/cocoon_spec.rb +++ b/spec/cocoon_spec.rb @@ -175,11 +175,16 @@ describe Cocoon do end end - context "association with conditions" do - it "should create correct association" do + context "create_object" do + it "should create correct association with conditions" do result = @tester.create_object(@form_obj, :admin_comments) result.author.should == "Admin" end + + it "should create correct association for belongs_to associations" do + result = @tester.create_object(stub(:object => Comment.new), :post) + result.should be_a Post + end end context "get_partial_path" do diff --git a/spec/dummy/app/models/comment.rb b/spec/dummy/app/models/comment.rb index 4e76c5b..c6666c8 100644 --- a/spec/dummy/app/models/comment.rb +++ b/spec/dummy/app/models/comment.rb @@ -1,3 +1,5 @@ class Comment < ActiveRecord::Base belongs_to :post + + attr_protected :author end