我有一个模型ShippingOption
,其中has_many ShippingSpeedOptions
还有一项要求:
ShippingOption
必须至少一个 ShippingSpeedOption
,并且应该验证这一点,因为它可以在界面中删除所以我在ShippingOption
上使用自定义验证:
def has_at_least_one_shipping_speed_option
errors.add(:shipping_speed_options, "Must have at least one delivery speed package") if self.shipping_speed_options.count <= 0
end
问题是,通过此验证,根本无法保存ShippingOption
,因为它没有ShippingSpeedOptions
。关联由shipping_option_id
中的ShippingSpeedOption
定义。
我该如何处理?
答案 0 :(得分:1)
使用build
,这会产生一个“等待中的关联”,这将在保存对象时创建。
@shipping_option = ShippingOption.new
@shipping_option.shipping_speed_options.build(:shipping_speed => <speed>)
@shipping_option.save
#at this point the validation is satisfied, @shipping_option is saved and the option is created.