0

我有一堆 activerecord 类,看起来很像我喜欢的!

我可以扩展一个基类来干燥方法,还是会混淆导轨?

也许我可以分享一些东西,但不能分享其他东西?

如果不是 - 最好的方法是什么?

非常感谢 ;)

class Stage < ActiveRecord::Base
  acts_as_taggable
  has_many :services, :as => :serviceable
  belongs_to :event
  belongs_to :user

  after_save :tag!

  def t(s)
    self.tag_list.add s
    self.event.tag_list.add s
  end

  # injected to after_save -> http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
  def tag!
    s = self

      if s.id > 0 then s.t "id-greater-than-0" end
      if s.id > 0 then s.t "some-stage-specific-stuff" end

    self.tag_list    
  end
end



class Sound < ActiveRecord::Base
  acts_as_taggable
  has_many :services, :as => :serviceable
  belongs_to :event
  belongs_to :user

  after_save :tag!

  def t(s)
    self.tag_list.add s
    self.event.tag_list.add s
  end

  # injected to after_save -> http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
  def tag!
    s = self

      if s.id > 0 then s.t "some-sound-specific-stuff" end

    self.tag_list    
  end
end
4

1 回答 1

3

您可以使用单表继承来解决此问题。本质上,您将拥有两个独立的模型,但它们将保存在同一个表中。除此之外,您可以将通用功能提取到父类中,并将细节留给子类。您可以在此处阅读有关 STI 的更多信息:http: //api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Single+table+inheritance

于 2012-01-31T12:19:34.337 回答