views:

851

answers:

2

I have a user model which has multiple addresses. Now for my application in rails, address is not mandatory. So, if someone wants to create a user and enter the address after the user has been created, my application should allow that. My problem is, for Address model I have validations for Address Line 1, City and Postal Code. These fields cannot be blank. When, editing a user, the following code fails:

user.addresses << Address.new

Rails tries to create a new Address and fires an Insert command. This is going to fail because of the validations that is required in the model. The above code doesn't fail if the user is not present in the database. One solution to this problem is to create a separate form_for binding for the edit partial for user. I don't want to do that solution. Is there any solution that allows me to bind an empty Address object for an already existing User object in the database ?

+3  A: 

Why attempt to add an empty Address object to the user.addresses collection? I think you could simply do something like:

user.addresses << Address.new unless (conditions)

I unfortunately don't know what your conditions are here, so it could be something like

user.addresses << Address.new unless params[:address].nil?

...although my guess is that you have a real Address object instead of just passing in a blank Address.new...

sammich
+2  A: 
user.addresses << Address.new

This code isn't going to work anyway if your Address model requires its fields to be set, because you're not supplying a hash to Address.new

If you want to add the address conditionally, you probably want something like this:

if !params[:address].blank?
  user.addresses.create(params[:address])
end

or

user.addresses << Address.new(params[:address]) unless params[:address].blank

If you really want to create an "empty" address object for each user (instead of just having users without addresses), you can change your validations so they only fire if the fields are filled out.

Something like this:

class Address < ActiveRecord::Base
  validates_presence_of :address1, :if => :non_empty_address?
  # etc

  private
    def non_empty_address?
     !address1.blank? || !address2.blank || !city.blank? # etc
    end
end

The restful_authentication plugin uses a similar approach to determine if the user's password is required.

Luke Francl
This helps me a lot. Thanks.