Inheritance in Ruby on Rails: setting the base class type
I am implementing a single table inheritance inside Rails. Here is the corresponding migration:
class CreateA < ActiveRecord::Migration
def self.up
create_tab开发者_如何学Cle :a do |t|
t.string :type
end
end
Class B inherits from A:
class B < A
end
Now, it's easy to get all instances of class B:
B.find(:all)
or
A.find_all_by_type("B")
But how do I find all instances of class A (those that are not of type B)? Is this bad organization?
I tried this:
A.find_all_by_type("A")
But instances of class A have a nil
type. I could do
A.find_all_by_type(nil)
but this doesn't feel right, somehow. In particular, it would stop working if I decided to make A inherit from another class.
Would it be more appropriate to define a default value for :type in the migration? Something like:
t.string :type, :default => "A"
Am I doing something wrong here?
The type field is more of a sub-type, this is why the ancestor class has a nil type.
You can actually set the type for a record of class A to 'A', and it will still behave properly, with a warm-fuzzy feeling. :)
class A
before_create :set_default_type
def set_default_type
self.type = self.class.name if type.blank?
end
end
精彩评论