如何为 belongs_to 同一模型的两个不同实例并需要其 ID 在 Factory Bot 中的方法编写工厂?
How to write a factory for a method that belongs_to two different instance of the same model and requires its id's in Factory Bot?
我有一个 User
模型,其中 has_many
个账户,每个 Account
belongs_to
一个用户和 has_many
个交易,每个 Transactions
两个不同的帐户(sender_account
和 recipient_account
),添加工厂的原始 belongs_to
方法(如 account
)将不起作用,因为我需要一个 sender_account
和recipient_account
.
如果我用 sender_account 1
和 运行 rpsec
手动设置 ID,我得到:
ActiveRecord::AssociationTypeMismatch:
Account(#5570447856500) expected, got 1 which is an instance of Integer(#5570414320800)
即使 ID 存储为 Integer
。
当我的模型 belongs_to
到同一模型的不同实例时,如何添加关联?
我已经定义了我的帐户和用户工厂,它们按预期工作。
ActiveRecord::AssociationTypeMismatch:
Account(#5570447856500) expected, got 1 which is an instance of Integer(#5570414320800)
实际上,这个错误表明,指定的是整数而不是帐户,因此我们可以将现有帐户 ID 指定为 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
这将使用 account
工厂
为 sender_account
和 recipient_account
协会创建一个帐户
我有一个 User
模型,其中 has_many
个账户,每个 Account
belongs_to
一个用户和 has_many
个交易,每个 Transactions
两个不同的帐户(sender_account
和 recipient_account
),添加工厂的原始 belongs_to
方法(如 account
)将不起作用,因为我需要一个 sender_account
和recipient_account
.
如果我用 sender_account 1
和 运行 rpsec
手动设置 ID,我得到:
ActiveRecord::AssociationTypeMismatch:
Account(#5570447856500) expected, got 1 which is an instance of Integer(#5570414320800)
即使 ID 存储为 Integer
。
当我的模型 belongs_to
到同一模型的不同实例时,如何添加关联?
我已经定义了我的帐户和用户工厂,它们按预期工作。
ActiveRecord::AssociationTypeMismatch:
Account(#5570447856500) expected, got 1 which is an instance of Integer(#5570414320800)
实际上,这个错误表明,指定的是整数而不是帐户,因此我们可以将现有帐户 ID 指定为 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
这将使用 account
工厂
sender_account
和 recipient_account
协会创建一个帐户