I’ve got a problem with designing my User model and making a decent form for it. I just want to ensure myself that I’m doing it wrong 🙂
So it goes like this:
User has got two Addresses:
- a mandatory
Addressfor identification and billing, - an optional shipping
Addressthat he could fill in or leave blank
I tried like this:
class User < ActiveRecord::Base
has_one :address
has_one :shipping_address, :class_name => 'Address', :foreign_key => 'shipping_address_id'
accepts_nested_attributes_for :address
accepts_nested_attributes_for :shipping_address
#validations for user
end
and:
class Address < ActiveRecord::Base
#validations for address
end
And then I make a form for User using form_for and nested fields_for. Like this:
= form_for @user, :url => '...' do |a|
= f.error_messages
...
= fields_for :address, @user.build_address do |a|
...
But then, despite that f.error_messages generates errors for all models, fields for Addresses don’t highlight when wrong.
Also I have problems with disabling validation of the second address when the user chose not to fill it in.
And I have doubts that my approach is correct. I mean the has_one relation and overall design of this contraption.
So the question:
Am I doing it wrong? How would You do that in my place?
What is wrong in your form is that it will build a new address every time the view is rendered, thus losing all validation errors.
In your controller, in the
newaction you should do something likeand in your view write:
Hope this helps.