Skip to content

Instantly share code, notes, and snippets.

@igor04
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igor04/7326ec61b3f082deca06 to your computer and use it in GitHub Desktop.
Save igor04/7326ec61b3f082deca06 to your computer and use it in GitHub Desktop.
example
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:...> ..]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment