Skip to content

Instantly share code, notes, and snippets.

@ream88
Created June 7, 2011 14:03
Show Gist options
  • Save ream88/1012314 to your computer and use it in GitHub Desktop.
Save ream88/1012314 to your computer and use it in GitHub Desktop.
Get STI models working with forms (you can assign the model's type directly)
<%= f.select(:type, ['User', 'Admin']) %>
module SingleTableInheritiance
def self.included(base)
base.extend(SingleTableInheritiance::ClassMethods)
base.attr_accessible(:type)
end
module ClassMethods
def new(*args, &block)
attributes = args.dup.extract_options!.with_indifferent_access
type = attributes.delete(:type)
if type.blank? || (type = type.constantize) == self
super(*args, &block)
else
super(*args, &block).becomes(type).tap do |object|
object.attributes = attributes
end
end
end
end
end
class User < ActiveRecord::Base
include SingleTableInheritance
class Admin < User
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment