Merb and Datamapper Single Table Inheritance

To begin add the Discriminator property to your model. I will be using User as my main model, and there will be an administrator and member model to inherit from it.

# app/models/user.rb
      class User
              include DataMapper::Resource
               ..
              property :type, Discriminator
      end
      
rake db:automigrate

Next, add your additional models based that will use the single table inheritance. You could create a separate models/model_name.rb for these, but I just lump them in with models/user.rb

# app/models/user.rb
      class User
              include DataMapper::Resource
              ..
              property :type, Discriminator
              ..
      end
      
      class Editor < User; end
      class Administrator < Editor; end
      

Now you can run commands like User.all, Administrator. all, and Editor.all. And to create a user with an Administrator role do something like the following.

User.create(:login => 'scottmotte', :password => 'password', :password_confirmation => 'password', :email => 'scott@scottmotte.com', :type => 'Administrator')

Finally, you need to add routes for the Editor and Administrator otherwise resource(user) will give you serious generation errors.

# router.rb
      resources :users
      resources :administrators, :controller => :users
      

Picture of Scott Motte

delicious facebook rss twitter

Spitfire Sky | github | archives | resume