我有一个具有以下关联的模型:-
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关联?
答案 0 :(得分:1)
您可以使用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