On Thursday, June 28, 2012 5:06:11 PM UTC-7, Jack wrote:
>
> I have a parent model, Product, that has many Variants. I'm using 
> nested_attributes on the Product model. On the Variants model I have a 
> presence validation on the :product. When I try to persist the product with 
> some :variants_attributes, I get a validation error saying:
>
> gems/sequel-3.36.1/lib/sequel/model/base.rb:1228:in `save': variants 
> product is not present (Sequel::ValidationFailed)
>
> If I remove that validation, the product_id gets set correctly in the 
> Variant table. Do I have to manually set the product_id somewhere so that 
> the validation can pass? It seems like the id is set on save, so the 
> validation fails because valid? is called before save.
>

Here's the probable order of events:

1) Product and Variants get validated
2) Product gets saved
3) Variants get saved

You are getting the error because the nested_attributes plugin does the 
validation of the associated objects at the same time it validates the 
current object, which is before saving the current object.  This is by 
design so that validation errors in associated objects prevent saving of 
the current object.

In the case of a new Product, the product's id will not be available until 
after saving, so it's not like you could cheat and assign the keys earlier 
in that case. You probably need to either remove that validation from 
Variant (or move the check into a before_save hook), or make it conditional 
and set some flag that disables it when it is being created via 
nested_attributes, i.e.:

  def variants_attributes=(vs)
    super
    associations[:variants].each{|v| v.check_product = false}
  end

Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/sequel-talk/-/oTotSMC8g68J.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sequel-talk?hl=en.

Reply via email to