views:

24

answers:

1

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?

A: 

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
Steven Soroka
How would you do that? BY setting it manually for every new A instance, or by defining a default type value?
Régis B.
example added ^^
Steven Soroka
I like that, even though I realise I am probably not using the right data model.
Régis B.