2013-04-11 30 views
0

我希望有一個名爲「transactions」的表,但具有不同的類(CashTransaction和CreditCardTransaction),並在「type」列中確定行是什麼。在RoR中建模現金,信用卡交易的最佳方式

有關如何做到這一點的任何建議?

+0

添加創建這些交易一個TransactionType表,其中一個PK與您的Transactions表中選定類型的FK相對應。 – 2013-04-11 18:44:17

回答

2

如果兩個交易類型都具有相同的屬性(表列),你可以使用STI,創建三個車型,如

class Transaction < ActiveRecord 
    # create table called transactions and add type column to it. 
    # add common methods inside this class 
end 

class CashTransaction < Transaction 
    # the type column will be CashTransaction and used to determine entry for this class in transactions table 
end 

class CreditCardTransaction < Transaction  
    # the type column will be CreditCardTransaction and used to determine entry for this class in transactions table 
end 

,然後你可以使用子類

CreditCardTransaction.new 
CreditCardTransaction.find 
#..etc 
# or 
CashTransaction.new 
CashTransaction.find ..