This file contains 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 | |
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:...> ..] |