Rails协会 - 至少有一个

时间:2014-04-03 09:31:30

标签: ruby-on-rails ruby database ruby-on-rails-3

我有一个模型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定义。

我该如何处理?

1 个答案:

答案 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.