Wednesday, September 17, 2014

Rails: STI (Single Table Inheritance)

class User < ActiveRecord::Base
has_many :animals
has_many :dogs
has_many :cats
end
class Zoo < ActiveRecord::Base
has_many :animals
has_many :elephants
end
class Animal < ActiveRecord::Base
# for STI should have additional field `type`
scope :domestic, -> { where("user_id IS NOT NULL").includes(:user) }
end
class Elephant < Animal
belongs_to :zoo
end
class Dog < Animal
belongs_to :user
end
class Cat < Animal
belongs_to :user
end
user = User.first
user.animals # -> [<Dog:...>, <Cat:...> ..]
user.dogs # -> [<Dog:...>, ..]
user.cats # -> [<Cat:...>, ..]
zoo = Zoo.first
zoo.animals # -> [<Elphant:...>, ..]
zoo.elephants # -> [<Elphant:...>, ..]
Animals.all # -> [<Dog:...>, <Cat:...>, <Elephants:..>, ..]
Dogs.all # -> [<Dog:...>, ..]
Cats.all # -> [<Cat:...>, ..]
Elephant.all # -> [<Elephants:...>, ..]
Animals.domestic # -> [<Dog:...>, <Cat:...> ..]
view raw animal.rb hosted with ❤ by GitHub

 
 
Blogger Templates