2
votes

I have a model ShippingOption, which has_many ShippingSpeedOptions

And one requirement:

  • A ShippingOption must have at least one ShippingSpeedOption, and this should be validated because it is removable in the interface

So I am using a custom validation on 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

The problem is that with this validation, a ShippingOption can't be saved at all because it has no ShippingSpeedOptions. The association is defined by the shipping_option_id in ShippingSpeedOption.

How should I deal with this?

1

1 Answers

1
votes

use build, which makes an "association in waiting", which will be created when the object is saved.

@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.