Inheritance in Ruby on Rails: setting the base class type
Posted
by Régis B.
on Stack Overflow
See other posts from Stack Overflow
or by Régis B.
Published on 2010-06-16T15:19:59Z
Indexed on
2010/06/16
15:22 UTC
Read the original article
Hit count: 273
ruby-on-rails
|inheritance
I am implementing a single table inheritance inside Rails. Here is the corresponding migration:
class CreateA < ActiveRecord::Migration
def self.up
create_table :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?
© Stack Overflow or respective owner