nested_attributes and many_to_one validations #523

Closed
kamui opened this Issue Jul 19, 2012 · 1 comment

Comments

Projects
None yet
2 participants

kamui commented Jul 19, 2012

I have an Order model that has a many_to_one relationship with a Shopper. Both have validations on them. I wanted to use nested_attributes to save the order, shopper, address, etc by calling save on an order and then having all validation errors available in each association in order.errors.

The problem I'm having is that when the relationship is a many_to_one on the model you're calling save on, it seems to only validate on the order model. The shopper and address validations don't seem to run at all.

I've created a gist to illustrate:
https://gist.github.com/3146430

I might be doing something wrong. Am I supposed to be manually creating the shopper, the address, then setting it on the order and then saving that? I have raise_on_save_failure = false and I was hoping to avoid that because it makes my controller code more complicated trying to return error arrays as save is called on each model. Any suggestions would be appreciated.

Owner

jeremyevans commented Jul 19, 2012

Validations on the associated object will only be called if nested_attributes is creating or updating the object. So in your gist, only o.save will check the associated object. Both o2 and o3 never touch shopper_attributes, so nested_attributes is not going to be called at all in those cases.

nested_attributes is not designed as a general purpose tool to validate associated objects. If the nested attributes code isn't creating or updating the associated record, it will not attempt to validate it. This is by design.

For example, if you add this code to your gist:

o4 = Order.new(quantity: 1, price_in_cents: 100_00, shopper_attributes:{})
o4.save
puts o4.errors

You can see how nested_attributes will do validations for associated objects that it is creating.

In the future, please ask questions about how to use Sequel on the sequel-talk Google Group. The GitHub bug tracker should be used only for reporting internal bugs in Sequel. Unless you are sure you've found an internal bug, it's best to ask first on sequel-talk.

Thanks,
Jeremy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment