Rails - 将模型与另一个模型的多个实例相关联时出现AssociationTypeMismatch错误

时间:2013-08-23 13:47:09

标签: ruby-on-rails

我有两个模型,帐户和CreditRecords。帐户可以包含许多属于它的信用记录。但是,帐户还可以将信用记录交易到其他帐户,我想跟踪当前帐户所有者是谁以及原始所有者是谁。

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都设置为整数。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我不确定您为什么要在account_id课程中为自己的关联account而非CreditRecord命名。这种方法的问题在于您的路径中有/将具有如下所示的嵌套资源:

resources :accounts do 
  resources :credit_records
end

您将获得/accounts/:account_id/credit_records/:id/...的网址格式,并且您的参数哈希将包含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