开发者

Drying up my rails models

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_m开发者_StackOverflowany :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


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.


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. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜