我有一个User模型,has_many帐户、每个Account belongs_to一个用户和has_many事务、每个Transactions到两个不同的帐户(sender_account和recipient_account),添加工厂的原始belongs_to方法(比如account)将不能工作,因为我需要一个sender_account和recipient_account。
如果使用sender_account 1手动设置ID并运行rpsec,则会得到:
ActiveRecord::AssociationTypeMismatch:
Account(#5570447856500) expected, got 1 which is an instance of Integer(#5570414320800)即使ID是以Integer形式存储的。
当我的模型belongs_to添加到同一模型的不同实例时,我如何添加关联?我已经定义了我的帐户和用户工厂,它们可以正常工作。
发布于 2018-08-12 06:00:38
ActiveRecord::AssociationTypeMismatch:
Account(#5570447856500) expected, got 1 which is an instance of Integer(#5570414320800)实际上,此错误表示,该整数是指定的,而不是帐户,因此我们可以将现有帐户ids指定为sender_account_id和recipient_account_id。
FactoryBot.define do
factory :transaction do
sender_account_id 1
recipient_account_id 2
end
end另一个解决方案是指定创建的关联的工厂:
FactoryBot.define do
factory :transaction do
association :sender_account, factory: :account
association :recipient_account, factory: :account
end
end这将使用sender_account工厂为recipient_account和account关联创建一个帐户。
https://stackoverflow.com/questions/51806014
复制相似问题