如何解决如何在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 => \'Center\'
has_many :invoice_document_lines,:invoice_document_lines
# Some configuration
accepts_nested_attributes_for :invoice_document_lines
acts_as_freezable :only_dependencies => true,:has_many => [:invoice_document_lines],:customer_center]
acts_as_clonable :has_many => [:invoice_document_lines]
# Validations
validates_each :lines do |record,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
。
您将如何在父类中重构此行为?
我可以将内容放入模块中并导入,但是整个文档层次几乎变得毫无用处。
我已经有了文档的层次结构,所以如果可以的话,我想在有办法的情况下使用它。
解决方法
您可以尝试使用Class.inherited
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。