![](/img/trans.png)
[英]Rails - Having multiple 'has_many through 'associations on the same model
[英]Rails factories having multiple associations to same object
我有一個這樣的關聯模型:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.