Use association build methods instead of assoc.klass.new. This avoids mass-assignment errors and other misbehaviors around attribute accessibility.

This commit is contained in:
Jeffrey Chupp 2012-05-04 19:25:59 -04:00
parent 251d326f31
commit 5ddefa399d
3 changed files with 16 additions and 5 deletions

View File

@ -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)

View File

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

View File

@ -1,3 +1,5 @@
class Comment < ActiveRecord::Base
belongs_to :post
attr_protected :author
end