Model Inheritance?

Hello,

I need some help with designing a model I have in mind. I’m not sure
what the best way to do it in Ruby/Rails is, or even if what I’m
thinking is possible.

Basically, I have a system where I want to treat everything as a
“message.” A Message is a basic model object with a title and
message_text. It can stand on it’s own, or it can be “converted” into a
more complex object like a task, or a project. Tasks and Projects all
have titles and message_text, so it seems silly to make them entirely
separate models, especially because I want to be able to easily convert
any message to a different type. But, tasks and projects will have
their own, separate data such as a start_date, end_date and more. From
a DB design standpoint it would seem logical to have a messsages table
and tasks and projects tables that would have a foreign key to a
message. But I’m not sure that makes sense in a Rails model. What is
the best way to represent this in Rails?

If you want Task and Project to be subclasses of Message, ActiveRecord
will expect you to store all three types of object in the same table
(‘messages’ by default). This table will need to be able to support
ALL of the data columns for each type (this is Single Table
Inheritance, or STI).

If the overlap between your subclasses is sufficiently small (i.e. the
only shared data is ‘title’ and ‘message_text’), I’d probably store
them in seperate tables and throw notions of inheritance out of the
window. In situations where you felt you might need to check
object.kind_of?(Message), you can simply slot in
object.respond_to?(:title) or object.respond_to?(:message_text),
should you feel it necessary to check that you’re dealing with the
right kind of object.

However, if the overlap is relatively big and each subclass only needs
to add a small amount of unique data, you might as well use STI.

It’s a judgement call really, and only you can make it! :slight_smile:

  • james

On 2/24/06, Brian D. [email protected] wrote:

have titles and message_text, so it seems silly to make them entirely


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

  • J *
    ~

However, if the overlap is relatively big and each subclass only needs
to add a small amount of unique data, you might as well use STI.

It’s a judgement call really, and only you can make it! :slight_smile:

James,

Thanks for the feedback. I was coming to this conclusion, although I
was reluctant to let go of my dreams :stuck_out_tongue: I think that STI will work
fine, especially for what I need right now. It’s one of those cases
where I am thinking way too far ahead. Gotta stick to the KISS
principle and cross that bridge if I come to it.

Thanks again,

Brian