2013-08-23 58 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

相关问题