Skip to content

Instantly share code, notes, and snippets.

@EvanBurchard
Created July 1, 2010 07:23
Show Gist options
  • Save EvanBurchard/459676 to your computer and use it in GitHub Desktop.
Save EvanBurchard/459676 to your computer and use it in GitHub Desktop.
Remember to set the parent model with all the attributes. There is no table for the sub models.
Ugh part one. From
http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html
Overwrite the child models' model_name method:
def self.model_name
name = "vehical"
name.instance_eval do
def plural; pluralize; end
def singular; singularize; end
end
return name
end
Make the parent know it's children:
def self.select_options
subclasses.map{ |c| c.to_s }.sort
end
@child_classes = []
def self.inherited(child)
@child_classes << child
super # important!
end
def self.child_classes
@child_classes
end
Fix development env to load classes
# add to config/environments/development.rb:
%w[vehicle car truck motorcycle].each do |c|
require_dependency File.join("app","models","#{c}.rb")
end
Also advised is to share a single controller (and resources) for the base class with all of the subclasses.
Ugh Part 2 From
http://stackoverflow.com/questions/1601739/rails-attr-accessible-does-not-work-for-type
Can't mass assign to the type attribute even if you have an attr_accessible. So much for principle of least surprise.
Here's one option:
def type_helper
self.type
end
def type_helper=(type)
self.type = type
end
That's kind of nasty.
Here's another option that I hate slightly less:
# in controller
def create
# assuming your select has a name of 'content_item_type'
params[:content_item_type].constantize.new(params[:content_item])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment