3
class Upload < ActiveRecord::Base
    has_many :comments
end

class Gallery < Upload
    has_many :images
end

class MusicAlbum < Upload
    has_many :audio_tracks
end

Should this work as expected? Will Gallery and MusicAlubm models inherit :comments association from their parent (Upload) and add their own?

Wojtek Kruszewski
  • 13,940
  • 6
  • 38
  • 38
  • 1
    One reason to declare all associations in base class will be ability to eager-load all associations when loading uploads. In other words I could do ```Upload.all include: [:comments, :images, :audio_tracks]``` – Wojtek Kruszewski Nov 20 '12 at 16:43

1 Answers1

5

Yes, the models are just classes, and when inherited they get all the methods from parent class. So, as both Gallery and MusicAlbum are descendants from Upload model, they will have the has_many :comments association, and both will get data from uploads db table (which needs to have a type column to support STI for this model)

A nice simple STI example can be found here

alony
  • 10,725
  • 3
  • 39
  • 46
  • I'm not worrying about inheriting methods, more about things like reflection. I fear issues like Rails expecting all associations are defined on base class and reflects on associations of only this class. The example does not customise associations in subclasses. Did you ever try that in a "real" project? Did it work without issues? – Wojtek Kruszewski Nov 20 '12 at 16:42
  • associations are just lists of methods which are generated by Rails and work certain way. So yes, it works for sure, it's no matter where the association is declared - in the model itself or in it's parent. Actually you can even declare it in a module and include that module into your class – alony Nov 20 '12 at 17:22
  • That's interesting about Modules, they only way I recall is to do it in "included" or "extended" callbacks which declares them in context of including classes. Do you know a way to have association methods defined in a module so that it could be included in a module (without callbacks?). There's more than defined methods, that much I know. Otherwise how would Model.reflections work? – Wojtek Kruszewski Nov 20 '12 at 21:45
  • Regardless of that, I'm accepting your answer. I asked if it's ok and you said "yes". The fact that I'm not convinced but can't verify your claim might indicated a problem with my question :P Moving association down into subclasses seem to work well in my project. – Wojtek Kruszewski Nov 20 '12 at 21:52