Permalink
Browse files

save polymorphic joins from the has_many|one association (closes #3812)…

… [Rick Olson]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@3586 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent b230004 commit a32a9863640dbd7a74b251e5467f90d134396110 @dhh dhh committed Feb 12, 2006
@@ -74,6 +74,15 @@ def extract_options_from_args!(args)
@owner.send(:extract_options_from_args!, args)
end
+ def set_belongs_to_association_for(record)
+ if @reflection.options[:as]
+ record["#{@reflection.options[:as]}_id"] = @owner.id unless @owner.new_record?
+ record["#{@reflection.options[:as]}_type"] = ActiveRecord::Base.send(:class_name_of_active_record_descendant, @owner.class).to_s
+ else
+ record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
+ end
+ end
+
def merge_options_from_reflection!(options)
options.reverse_merge!(
:group => @reflection.options[:group],
@@ -13,7 +13,7 @@ def build(attributes = {})
else
load_target
record = @reflection.klass.new(attributes)
- record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
+ set_belongs_to_association_for(record)
@target << record
record
end
@@ -140,7 +140,7 @@ def cached_counter_attribute_name
end
def insert_record(record)
- record[@reflection.primary_key_name] = @owner.id
+ set_belongs_to_association_for(record)
record.save
end
@@ -42,8 +42,7 @@ def replace(obj, dont_save = false)
@target = nil
else
raise_on_type_mismatch(obj)
-
- obj[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
+ set_belongs_to_association_for(obj)
@target = (AssociationProxy === obj ? obj.target : obj)
end
@@ -56,6 +56,28 @@ def test_polymorphic_has_one_create_model_with_inheritance
assert_equal "Post", tagging.taggable_type
end
+ def test_set_polymorphic_has_many
+ tagging = tags(:misc).taggings.create
+ posts(:thinking).taggings << tagging
+ assert_equal "Post", tagging.taggable_type
+ end
+
+ def test_set_polymorphic_has_one
+ tagging = tags(:misc).taggings.create
+ posts(:thinking).tagging = tagging
+ assert_equal "Post", tagging.taggable_type
+ end
+
+ def test_create_polymorphic_has_many_with_scope
+ tagging = posts(:welcome).taggings.create(:tag => tags(:general))
+ assert_equal "Post", tagging.taggable_type
+ end
+
+ def test_create_polymorphic_has_one_with_scope
+ tagging = posts(:welcome).tagging.create(:tag => tags(:general))
+ assert_equal "Post", tagging.taggable_type
+ end
+
def test_has_many_with_piggyback
assert_equal "2", categories(:sti_test).authors.first.post_id.to_s
end

0 comments on commit a32a986

Please sign in to comment.