2016-01-23 82 views
1

他在那里,Rails 4 - 两个相似的模型 - 实现它们的最佳实践?

我想知道我怎么能实现两个模型是70%相似,但与一些不同的列。

在应用程序中,我可以创建一个有很多截止日期的合同。我有几种类型的合同,根据这些类型,我的截止日期模型应该有点不同。例如,如果合同类型为'财务',则其截止日期将由“日期”,“金额”和“状态”组成;如果合同类型为“财务”,则其期限将由“日期”,“金额”和“状态”组成。而如果合同类型为“一般”,则其截止日期将由“日期”,“收到状态”和“状态”组成。

这两种型号共享“日期”和“状态”列。我有其他几种合同。

我应该创建一个单一的模型期限与所有的列? 我应该为每种合约类型创建一个Model DeadlineFinancial,DeadlineGeneral,...吗? 另一个解决方案?

非常感谢:)

+2

听起来像你想看看['Single Table Inheritance'](http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html)。如果你愿意的话,我可以写出它,尽管它不会是直接的答案 –

+0

有了STI,获得has_many的容易性:合同,然后是合同子类型的范围 - 以及将共享逻辑放入基类中很好..看到https://eewang.github.io/blog/2013/03/12/how-and-when-to-use-single-table-inheritance-in-rails/ – Tim

+0

非常感谢,我要去请看看:) –

回答

0

有关使用composed_of

http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html

创建(Common)Deadline类如何,

class Deadline 
    attr_reader :date, :status 

    def initialize(date, status) 
     @date, @status = date, status 
    end 

    # write common method 
end 

class GeneralDeadline < Deadline 
    attr_read :received_status 

    def initialize(date, status, received_status) 
    super(date, status) 
    @received_status = received_status 
    end 
end 

class FinancialDeadline < Deadline 
    def initialize(date, status, received_status) 
    super(date, status) 
    @amount = amount 
    end 

    # define method! 
end 

并定义composed_of

class GeneralContract 
    composed_of :deadline, class_name: 'GeneralDeadline', mapping: [%w(received_status received_status), %w(date date), %w(status status)] 
end 

class FinancialContract 
    composed_of :deadline, class_name: 'FinancialDeadline', mapping: [%w(amount amount), %w(date date), %w(status status)] 
end 
协会
+0

我要研究这个。非常感谢 :) –