Created
July 25, 2009 10:20
-
-
Save mitchellh/154763 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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