By default, ActiveRecord’s polymorphic associations allow any type to be set. In practice, it is often only a subset of types that should actually be allowed in the association. This plugin adds an :allow
option to the belongs_to
class method, which will raise an ActiveRecord::AssociationTypeMismatch
error if a non-allowed type is passed into the association. This is the same exception that is raised if you pass an object of the wrong type into a non-polymorphic association.
If a bogus class name is passed into the XXX_type=
method for a polymorphic association, no exception is raised (certain validations will then cause a NameError to be raised, though). Since in a standard Rails use-case none of the application code will explicitly deal with that attribute value, there’s no DRY way to make sure that a legit class name is being passed in. With this plugin installed, the setter fails fast, raising an ActiveRecord::AssociationTypeNameError
(this is a new one) if the class name does not exist. That way, your application can easily catch the error in a #rescue_action
implementation.
$ sudo gem install outoftime-polymorphic_type_restrictions --source=http://gems.github.com
Then in your config/environment.rb
config.gem 'outoftime-polymorphic_type_restrictions', :lib => 'polymorphic_type_restrictions'
Just use the :allow
key for belongs_to
:
class Comment belongs_to :commentable, :polymorphic => true, :allow => %w(Commentable Photo) end
The allowed types can indicate a concrete class, a superclass, or an included module.
-
Mat Brown <[email protected]>
-
Adam Hooper <[email protected]>
Polymorphic Type Restrictions is released under the MIT License, copyright © 2009 Mat Brown.