Skip to content

Instantly share code, notes, and snippets.

@mitchellh
Created July 25, 2009 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchellh/154763 to your computer and use it in GitHub Desktop.
Save mitchellh/154763 to your computer and use it in GitHub Desktop.
# Allow the "type" field to be mass assigned. This is useful
# for, in my case, nested model forms. It IS dangerous but
# with proper form validation on this type field, it should be
# safe.
class Friend < ActiveRecord::Base
# Basic validation of the type field
validates_format_of inheritance_column, :with => /^Friend::([A-Z][a-zA-Z]+)$/
# More validation for the type field to be safe
def validate
if errors.on(self.class.inheritance_column).empty?
begin
Kernel.const_get(type)
rescue NameError
errors.add(:type, "should not be some sneaky value.")
end
end
end
private
# The sneaky snake trick to allow "type" magic column
# to work with nested model forms.
def attributes_protected_by_default
super - [self.class.inheritance_column]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment