我有一個標準的has_many
關係(預訂有很多訂單),並驗證預訂在沒有至少一個訂單的情況下無法保存。我試圖用我的FactoryGirl工廠複製這個,但驗證正在阻止我這樣做。FactoryGirl has_many與驗證關聯
class Booking < ActiveRecord::Base
has_many :orders
validates :orders, presence: true
end
class Order < ActiveRecord::Base
belongs_to :booking
end
這裏是我的FactoyGirl出廠規格爲每個模型從FactoryGirl的GitHub的wiki頁面緊隨其後。
FactoryGirl.define do
factory :booking do
factory :booking_with_orders do
ignore do
orders_count 1
end
before(:create) do |booking, evaluator|
FactoryGirl.create_list(:order, evaluator.orders_count, booking: booking)
end
end
end
factory :order do
booking
end
end
當我試圖從我的規格運行FactoryGirl.create(:booking_with_orders)
,我得到:
Failure/Error: @booking = FactoryGirl.create(:booking_with_orders)
ActiveRecord::RecordInvalid:
Validation failed: Orders can't be blank
這似乎是在檢查甚至before(:create) [...]
其理論上將創建預訂的訂單之前運行驗證。
This post建議不要將has_many
關係添加到您的工廠,但是我想解決這個問題,無論如何,如果有一個好的方法來做到這一點。
在此先感謝。
您的意思是'booking.orders <<',否則,這是我的答案。謝謝! – Jalada
哎呀!修好了,謝謝指出 – jassa
優秀!非常感謝! – gayavat