FactoryGirl has_many association with validation

你。 提交于 2019-11-28 07:33:04

Wat? Impossible? Not at all.

Just change your code to something like this:

after :build do |booking, evaluator|
  booking.orders << FactoryGirl.build_list(:order, evaluator.orders_count, booking: nil)
end

Taking off from @jassa's answer, if you just need to add a single (required) associated record with a specific attribute, this pattern worked for me:

factory :booking do
  ignore do
    order_name "name"
  end

  after :build do |factory, evaluator|
    factory.orders << FactoryGirl.build(:order, name: evaluator.order_name, booking: nil)
  end
end

This seems like an overly simplistic observation but what you're trying to do is in effect make sure that the Order exists before the Booking, which is impossible, as the Order cannot exist without its booking_id (meaning that the Booking needs to be created first).

There's nothing wrong with a has_many relationship in your factories, it's your validation that is a problem. Does this currently work in your application? How do you save your records in that case? What is the flow for creating Orders and Bookings?

Even the infamous accepts_nested_attributes_for won't help you here.

My advice is to rethink your record saving and validation strategy so that it is a little more sane.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!