Project

has_sti

0.0
No commit activity in last 3 years
No release in over 3 years
has_sti provides helper methods for Single Table Inheritance models of Active Record. It creates methods that allow to determine exact type of model and scopes that make easy to find records of certain type.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

>= 4.0.0
 Project Readme

Build Status Gem Version

has_sti

has_sti is an ActiveRecord extension that provides helper methods and scopes for STI models.

Installation

  • Add has_sti to your Gemfile:
gem 'has_sti'
  • Install with: bundle install

Usage

We will use Ruby on Rails for this scenario. Let's say User model is a parent STI class and you want to create child classes: Admin and Reader. You start with defining STI as follows:

class User < ActiveRecord::Base
end

class Admin < User
end

class Reader < User
end

Next step is creating migration for the database: rails generate migration AddTypeToUser type:string

Then, we need to migrate database: bundle exec rake db:migrate

Basic setup of STI is done. Here's where has_sti takes action.

Modify your User model to include has_sti:

class User < ActiveRecord::Base
  has_sti :admin, :reader
end

And that's it. Now you have following methods and scopes available:

some_admin = Admin.create

some_admin.admin? => true
some_admin.reader? => false

User.admin => [some_admin]
User.reader => []

You can also disable helper methods:

class User < ActiveRecord::Base
  has_sti :admin, :reader, helper_methods: false
end

or scopes:

class User < ActiveRecord::Base
  has_sti :admin, :reader, scopes: false
end

or even set it per child class:

class User < ActiveRecord::Base
  has_sti :admin, scopes: false
  has_sti :reader, helper_methods: false
end

No configuration is required. Custom STI column name is supported.

License

has_sti is released under the MIT license:

Author

Arkadiusz Fal

Copyright © 2015