【问题标题】:How do I abstract similar validations/relations to parent class in Ruby/Rails?如何在 Ruby/Rails 中抽象出与父类类似的验证/关系?
【发布时间】:2011-09-05 19:10:09
【问题描述】:

我有这些非常相似的课程:

class DeliveryDocument < CommercialDocument
  # Relations
  belongs_to :biller, :class_name => 'Company'
  belongs_to :customer, :class_name => 'Company'
  belongs_to :customer_center, :class_name => 'Center'
  has_many :delivery_document_lines, :dependent => :destroy
  alias_attribute :lines, :delivery_document_lines
  # Some configuration
  accepts_nested_attributes_for :delivery_document_lines
  acts_as_freezable :only_dependencies => true,
    :has_many => [:delivery_document_lines],
    :belongs_to => [:biller, :customer, :customer_center]
  acts_as_clonable :has_many => [:delivery_document_lines]
  validates_each :lines do |record, attr, value|
    # ...
  end
end

还有:

class InvoiceDocument < CommercialDocument
  self.
  # Relations
  belongs_to :biller, :class_name => 'Company'
  belongs_to :customer, :class_name => 'Company'
  belongs_to :customer_center, :class_name => 'Center'
  has_many :invoice_document_lines, :dependent => :destroy
  alias_attribute :lines, :invoice_document_lines
  # Some configuration
  accepts_nested_attributes_for :invoice_document_lines
  acts_as_freezable :only_dependencies => true,
    :has_many => [:invoice_document_lines],
    :belongs_to => [:biller, :customer, :customer_center]
  acts_as_clonable :has_many => [:invoice_document_lines]
  # Validations
  validates_each :lines do |record, attr, value|
    # ...
  end
end

我还有一些我没有粘贴的方法可以提取到父级。我只需要知道父类中的类名。当我这样做时:

class CommercialDocument < Document  # document inherits from AR::Base
  # ...
  has_many :"#{self.to_s.underscore}_lines", :dependent => :destroy
  # ...
  accepts_nested_attributes_for :"#{self.to_s.underscore}_lines"
  # ...
end

它不起作用,因为self.to_sCommercialDocument

你会如何在父类中重构这种行为? 我可以将东西放在一个模块中并导入它,但随后整个文档层次结构变得几乎毫无用处。 我已经有了文档的层次结构,所以如果可以的话,如果有办法,我想使用它。

【问题讨论】:

    标签: ruby validation refactoring parent database-relations


    【解决方案1】:

    你可以试试Class.inherited

    【讨论】:

    • 我想我不能使用 Class.inherited。在完全评估完子代码之后调用它。有些方法我无法重构,但它们需要这种关系才能发挥作用。
    • 不确定我是否理解它为什么不起作用。您在继承的方法中尝试过类似subclass.send :has_many, :"#{subclass.to_s.underscore}_lines" 的方法吗?
    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多