0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

It does not change the problem with : proc { |attrs| attrs.all? { |k, v| v.blank? } } That should reject any blank field i can still pass my update_attributes method. Once again the validation of adress is ignored only at creation of adress
Thanks for the reject_if indication. Without reject_if in my accepts_nested_attributes_for line, it actually works as intended.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.