Created
June 7, 2011 14:03
-
-
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)
This file contains hidden or 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
<%= f.select(:type, ['User', 'Admin']) %> |
This file contains hidden or 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
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 |
This file contains hidden or 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
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