gpt4 book ai didi

ruby-on-rails - Rails 工厂与同一对象有多个关联

转载 作者:行者123 更新时间:2023-11-28 21:19:19 27 4
gpt4 key购买 nike

我有一个模型有这样的关联:-

 class Order < ApplicationRecord
belongs_to :customer, inverse_of: :orders
belongs_to :user, inverse_of: :orders
belongs_to :shipping_address, class_name: "Customer::Address", inverse_of: :shipped_orders
belongs_to :billing_address, class_name: "Customer::Address", inverse_of: :billed_orders
end

此外,customer_address 有一个字段 customer_id。我的工厂是这样的:-

FactoryGirl.define do
factory :order do
customer
user
association :shipping_address, factory: :customer_address, customer_id: customer.id
association :billing_address, factory: :customer_address, customer_id: customer.id
end
end

但我无法访问 customer.id。我收到此错误:-

undefined method `id' for #<FactoryGirl::Declaration::Implicit:0x007fa3e6979d70>

如何将 customer.id 传递给 shipping_address 和 billing_address 关联?

最佳答案

您可以使用 after(:build) 回调来构建您的 customer_address 记录。

FactoryGirl.define do
factory :order do
association :customer
association :user
after(:build) do |order|
order.shipping_address = FactoryGirl.build(:customer_address, customer_id: order.customer_id)
order.billing_address = FactoryGirl.build(:customer_address, customer_id: order.customer_id)
end
end
end

关于ruby-on-rails - Rails 工厂与同一对象有多个关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53993469/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com