Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails-AssociationTypeMismatch将一个模型与另一个模型的多个实例关联时出错_Ruby On Rails - Fatal编程技术网

Ruby on rails Rails-AssociationTypeMismatch将一个模型与另一个模型的多个实例关联时出错

Ruby on rails Rails-AssociationTypeMismatch将一个模型与另一个模型的多个实例关联时出错,ruby-on-rails,Ruby On Rails,我有两个模型,账户和信用记录。一个帐户可以有许多属于它的信用记录。但是,帐户也可以将信用记录交换给其他帐户,我希望跟踪当前帐户所有者是谁,以及原始所有者是谁 class Account < ActiveRecord::Base has_many :credit_records class CreditRecord < ActiveRecord::Base belongs_to :original_owner_id, :class_name => "Account" belon

我有两个模型,账户和信用记录。一个帐户可以有许多属于它的信用记录。但是,帐户也可以将信用记录交换给其他帐户,我希望跟踪当前帐户所有者是谁,以及原始所有者是谁

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"

帐户id和原始所有者id都设置为整数。

原始帐户id需要帐户对象。您不能设置id

credit_record.original_owner = account
credit_record.account = account

请将您的关联重命名为以下名称

class CreditRecord < ActiveRecord::Base
belongs_to :original_owner, :foreign_key => "account_id", :class_name => "Account"
belongs_to :account
class-CreditRecord“帐户id”,:类名称=>“帐户”
属于:帐户

我不知道你为什么要在
信用记录
类中命名你的协会
帐户id
而不是
帐户
。这种方法的问题是,当您的路由中有/将有如下嵌套资源时:

resources :accounts do 
  resources :credit_records
end
您将获得一个URL模式,即
/accounts/:account\u id/credit\u records/:id/…
,并且您的params散列将包含
account\u id
参数

建议按照@vimsha在其回答中的建议更新您的关联

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

好啊刚刚试过,现在我得到了这个:“NameError:未定义的局部变量或#的方法'foreign_key'”很抱歉。修改了我的答案。我明白了,它应该是一个符号。感谢您对路由的解释。我已将协会更改为account。
resources :accounts do 
  resources :credit_records
end
class CreditRecord < ActiveRecord::Base
  belongs_to :original_owner, :class_name => Account, :foreign_key => 'account_id'
  belongs_to :account, :class_name => Account
end
# Set account's id
credit_record.account.id = 1

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