2

trying to figure out the best ActiveRecord inheritance strategy for this particular problem:

I have an abstract class, let's call it Message with the following methods/attributes.

Message
  |- recipient
  |- sender
   \ body

And I have two sub classes

ColorMessage < Message
  |- first_color
  |- second_color
   \ body (returns "#{sender.name} says #{first_color} > #{second_color}")

WeatherMessage < Message
  |- current_weather_adverb
   \ body (returns "#{sender.name} enjoys #{current_weather_adverb} weather")

I'd like to be able to run a query for all Messages and display their bodies without having to worry about their concrete types. Basically treating Message as an interface.

I am familiar with STI, is that the correct solution in this case?

Thanks for your help!

Tyler
  • 4,679
  • 12
  • 41
  • 60

1 Answers1

1

I consider this an appropriate use for single-table-inheritance (STI(.

You can ask for Message.all or ColorMessage.all and rails will take care of the object casting for you.

Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109