当使用Factory Girl通过嵌套属性创建一个模型对象时,我一直在努力设置has_many / through关系。
class CommercialInvoice < ActiveRecord::Base
has_many :shipment_commercial_invoices, :dependent => :destroy
has_many :shipments, :through => :shipment_commercial_invoices
end
class Shipment < ActiveRecord::Base
has_many :shipment_commercial_invoices, :dependent => :destroy
has_many :commercial_invoices, :through => :shipment_commercial_invoices
end
class ShipmentCommercialInvoices < ActiveRecord::Base
attr_accessible :job_id, :detail_id
belongs_to :shipment
belongs_to :commercial_invoice
end
使用另一个模型supplier_invoice
中的嵌套属性创建Shipment模型class SupplierInvoice < ActiveRecord::Base
has_many :shipments, :dependent => :destroy
accepts_nested_attributes_for :shipments, :allow_destroy => true
end
class Shipment < ActiveRecord::Base
belongs_to :supplier_invoice
end
我的工厂
factory :supplier_invoice do do
shipments_attributes do
shipments_attributes = []
2.times do # 2 shipments per supplier invoice
shipments_attributes << attributes_with_foreign_keys(:shipment)
end
shipments_attributes
end
end
factory :commercial_invoice do
after(:create) do |commercial_invoice, evaluator|
commercial_invoice.shipments << FactoryGirl.create(:supplier_invoice).shipments
end
end
factory :shipments_commercial_invoice do
shipment
commercial_invoice
comm_invoiced true # A boolean attribute that i want to be true
end
现在每当我创建新商业发票时出现问题,相关的shipment_commercial_invoice属性 comm_invoiced始终为false 。我无法弄清楚我做错了什么。我如何定义工厂有什么问题吗?提前谢谢。