Say I have a table animals that has a column parent_id Say also that I have a type_id on the table to indicate species
So in my Animal class, Animall.all would return all animals.
Say that now I add two new animal types, dog and cat in the animal_types table. So now some animals have type_id of 1 and some 2.
I could write a named_scope on Animal to return all cats or all dogs.
But what if I wanted to go the route of creating cat and dog classes that reference the animals table, so in dog class, dog.all should issue a query, select * from animals where type_id = 1
开发者_如何学JAVAThen say I create a class called person, and added a has_many :dogs relationship
How can I make this work?
The way in rails to do this is STI (single Table inheritance). Short answer is your add a type field to the table, and then subclass animal.
see http://api.rubyonrails.org/classes/ActiveRecord/Base.html
so in your case you would have.
class Animal < ActiveRecord::Base; end
class Dog < Animal; end
class Cat < Animal; end
精彩评论