views:

72

answers:

2

I have a couple of models which share a has_many associations, named scopes and validations.

What's the best way of drying these models up so they can share the same code?

Create a parent class and have these models inherit from that or would I be better off creating a module?

This is the type of code I'm looking to dry up:

has_many :comments, :as => :commentable

has_permalink :title

validates_presence_of :title

has_attached_file :image

I've already figured that I can use this in a module to handle the has_many associations but when I try something similar with has_permalink or has_attached_file then things break down.

def self.included(klass)
  klass.has_many :comments, :as => :commentable
end
+2  A: 

You should use inheritance only if the models are true subtypes of some parent type, rather than as a convenient way to share code. Unlike some languages, Ruby has the module mechanism for the latter.

John Topley
Thanks John. It sounds like a module is the way to go.
KJF
+2  A: 

In rails inheritance implies shared database structure, not just convenience. So like John said, you really only want to do it when they're so similar that they can share the same table with a couple extra fields tacked on here and there.

If you aren't looking for single-table inheritance then mixing in a module is certainly a great way to go and it's super easy. :)

Chuck Vose
Thanks, I've tried the module route and have had some success with drying up the has_many associations but it breaks down if I try to dry up other code in the same way.
KJF