Skip to content

outoftime/polymorphic_type_restrictions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Polymorphic Type Restrictions

Purpose

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.

Also…

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.

Installation

$ 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'

Usage

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.

Contributors

License

Polymorphic Type Restrictions is released under the MIT License, copyright © 2009 Mat Brown.

About

Restrict types that ActiveRecord polymorphic associations can accept

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages