2013-08-23 56 views
0

我有兩個模型,Accounts和CreditRecords。一個賬戶可以有許多屬於它的信用記錄。但是,帳戶也可以將信用記錄交易到其他帳戶,並且我想要跟蹤當前帳戶所有者是誰,以及原始所有者是誰。Rails - 關聯一個模型與另一個模型的多個實例的AssociationTypeMismatch錯誤

class Account < ActiveRecord::Base 
has_many :credit_records 

class CreditRecord < ActiveRecord::Base 
belongs_to :original_owner_id, :class_name => "Account" 
belongs_to :account_id, :class_name => "Account" 

當我嘗試設置CreditRecord.account_id,比方說,1,它更新的罰款。但是,如果我嘗試CreditRecord.original_owner_id設置爲3,我得到這個錯誤:

ActiveRecord::AssociationTypeMismatch: Account(#70154465182260) expected, got Fixnum(#70154423875840) 

兩個ACCOUNT_ID和original_owner_id被設置爲整數。

回答

0

original_account_id正在等待一個帳戶對象。你不能設置一個ID。

credit_record.original_owner = account 
credit_record.account = account 

credit_record.account_id = account.id 

請重命名您的關聯以下

class CreditRecord < ActiveRecord::Base 
belongs_to :original_owner, :foreign_key => "account_id", :class_name => "Account" 
belongs_to :account 
+0

確定。剛剛嘗試過,現在我已經得到了:「NameError:未定義的局部變量或方法'foreign_key'爲#」 – krstck

+0

對不起。修改了我的答案。它應該是一個符號 – usha

+0

輝煌!這樣可行! – krstck

0

我不知道爲什麼要在CreditRecord類命名協會account_id,而不是僅僅account 。這種方法的問題是,當你/將嵌套的資源,如在你的路線如下:

resources :accounts do 
    resources :credit_records 
end 

你會得到一個URL圖案/accounts/:account_id/credit_records/:id/...,和您的PARAMS哈希將在它account_id參數。

建議按照@vimsha在他的回答中所建議的那樣更新您的關聯。

class CreditRecord < ActiveRecord::Base 
    belongs_to :original_owner, :class_name => Account, :foreign_key => 'account_id' 
    belongs_to :account, :class_name => Account 
end 

這將允許你通過像信用記錄對象分配帳戶的id屬性:

# Set account's id 
credit_record.account.id = 1 

# Set original_owner's id 
credit_record.original_owner.id = 2 
+0

啊,我明白了。感謝關於路由的解釋。我已將該關聯更改爲帳戶。 – krstck

相關問題