Skip to content
Browse files

Ensure subtype value is always accessible on parent association

  • Loading branch information...
1 parent ea7706b commit 07de0977ad5abea6574f1f2188efd716c69993de @mhuggins committed Mar 31, 2012
Showing with 12 additions and 12 deletions.
  1. +12 −12 lib/multiple_table_inheritance/child/base.rb
View
24 lib/multiple_table_inheritance/child/base.rb
@@ -25,15 +25,11 @@ def inherits_from(association_name, options={})
self.parent_association_name = association_name.to_sym
self.primary_key = "#{parent_association_name}_id"
- # Ensure parent association is always returned.
- define_method("#{parent_association_name}_with_autobuild") do
- send("#{parent_association_name}_without_autobuild") || send("build_#{parent_association_name}")
- end
+ define_parent_association_builder
# Bind relationship, handle validation, and save properly.
belongs_to parent_association_name, options
alias_method_chain parent_association_name, :autobuild
- before_validation :set_association_subtype
validate :parent_association_must_be_valid
before_save :parent_association_must_be_saved
end
@@ -47,6 +43,17 @@ def parent_association_class
private
+ def define_parent_association_builder
+ subtype_column = parent_association_class.subtype_column
+ define_method("#{parent_association_name}_with_autobuild") do
+ unless association = send("#{parent_association_name}_without_autobuild")
+ association = send("build_#{parent_association_name}")
+ association.send("#{subtype_column}=", self.class.to_s)
+ end
+ association
+ end
+ end
+
def inherited_columns_and_associations
# Get the associated columns and relationship names
inherited_columns = parent_association_class.column_names - column_names
@@ -129,13 +136,6 @@ def parent_association=(record)
send("#{parent_association_name}=", record)
end
- def set_association_subtype
- association = parent_association
- if association.attribute_names.include?(association.class.subtype_column)
- association[association.class.subtype_column] = self.class.to_s
- end
- end
-
def parent_association_must_be_valid
association = parent_association

0 comments on commit 07de097

Please sign in to comment.
Something went wrong with that request. Please try again.