Syl
Syl

Reputation: 3829

Validates and nested forms

my ruby on rails 3.0.3 app display an empty address form when showing the cart to a customer.

The addresse module ask the presence of all fields :

validates :nom,:prenom,:adresse,:code_postal,:ville,:email, :presence => true

If I validate an empty form it works despite validate condition. I complete the forms, go to next page and comes back to the now populated creation form. Now if i remove a field the valiates is taken into account.

Here is my empty address creation code for the nested form in the show action :

if (@cartshowed.adresse_client.nil?)
        @cartshowed.build_adresse_client
      end

I guess that when usind the empty address validation is ignored, but as soon as i validate data for an already valid adress it works.

How can i have validation working when i create the address, and not only for edition ?

PS : The edition/creation is done on the same page through the same controllers. Edition was not intended to exist but it works.

EDIT : After several try i think my problem is that creating adresse through nested forms completly overiddes validates field in address. How can i kee validates restriction in a nested form?

Upvotes: 0

Views: 748

Answers (2)

Syl
Syl

Reputation: 3829

It seems that as soon as i use reject_if the validation of my children model is not totaly taken into account. Removing the reject_if resolved all my problems. Now an empty form or a form not conform to the validates requirement is correctly rejected at the update_attributes step in the controller.

Upvotes: 0

kwarrick
kwarrick

Reputation: 6190

If Addresse is a nested attribute (i.e. Cart has_one Address), perhaps you should use the accepts_nested_attributes_for which allows you to add a :reject_if Proc.

accepts_nested_attributes_for :addresse, :reject_if => :any_blank 

I couldn't give a better example than Ryan Daigle:

http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

Upvotes: 1

Related Questions