Using inheritance with RoR
I'm working on my first Rails application (my first Ruby application, for that matter) and I have a question about inheritance. I have to be able to load physical media and I want to store physical properties separately in the database so that some attributes can be queried outside of the application as easily as inside. To manage this, I have a table images
and a binaries
. The former stores metadata specific to images, of course, while the latter stores physical file metadata that will apply to a range of file types. After my approach is solid, I will add a table swfs
, a table, videos
and possibly others.
At the moment, my class is BinaryObserver
grabbing the before_create
image callback and loading the physical file - the binary. This works great, but I'm wondering what other approaches are. In particular, I'm wondering if I can't (and shouldn't) establish a base inheritance model where Binary
extends ActiveRecord::Base
and Image
extends Binary
.
Like now, Image belongs_to Binary
and Binary has_one Image
. Since there is an obvious relationship is-a
, should I use inheritance? Does rails support this kind of support when interacting with a database? This might be the best way to reduce the amount of work required to support the new file type.
Any thoughts or suggestions on this would be needed. I am experimenting with language and framework, so I try to learn best practices before I go deeper.
Thank.
source to share
Fortunately, there is very nice single table inheritance built into rails.
Unfortunately what you are looking for is multi-table and the support is pretty gloomy.
Check out some examples of how people have implemented such features:
http://zackham.com/2008/8/21/multiple-table-inheritance
http://github.com/sava/class_table_inheritance/tree/master
http://github.com/rwl4/inherits_from/tree/master
Or, you can just switch to unidirectional inheritance (although that beats your previous comment):
class Binary < ActiveRecord::Base
end
class Image < Binary
end
and add this to your binary model:
type VARCHAR(20) NOT NULL
Examples:
@binaries = Binary.find(:all)
@images = Image.find(:all)
source to share
From a DB perspective .. You don't need a binary table ... if you are storing binary data in a database it's just a date like a property. You wouldn't make a date table :)
Say Image expands binary because image "is-a" is binary inaccurate, image is "created from" binary like Person made from Flesh (you wouldn't say Person is extlesh Flesh)
Anyway, there is a plugin for attachments: attachment_fu , use it :)
source to share