如何在Ruby / Rails中抽象与父类相似的验证/关系?
|
我有这些非常相似的课程:
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_s
是CommercialDocument
。
您将如何在父类中重构此行为?
我可以将内容放入模块中并导入,但是整个文档层次几乎变得毫无用处。
我已经有了文档的层次结构,所以如果可以的话,我想在有办法的情况下使用它。
没有找到相关结果
已邀请:
1 个回复
括宠