Rails ActiveRecord Update question
I have a user model that has multiple addresses. Now for my app in rails, the address is optional. So, if someone wants to create a user and enter an address after the user has been created, my application should allow that. My problem is, for the address model, I have checks for address bar 1, city and postal code. These fields cannot be empty. When, while editing the user, the following code fails:
user.addresses <Address.new
Rails tries to create a new address and runs the Insert command. This will fail due to the validation required in the model. The above code does not fail if the user is not present in the database. One solution to this problem is to create a separate binding form for partial editing for the user. I don't want to make this decision. Is there any solution that allows me to bind an empty Address object to a pre-existing User object in the database?
source to share
Why try to add an empty Address object to the user.addresses collection? I think you could just do something like:
user.addresses << Address.new unless (conditions)
Unfortunately, I don't know what your conditions are here, so it might be something like
user.addresses << Address.new unless params[:address].nil?
... although I am assuming you have a real address object and not just a space in the Address.new address ...
source to share
user.addresses << Address.new
This code will not work anyway if your address model requires its fields to be set, because you are not supplying the hash Address.new
If you want to add an 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 that they only run when fields are filled.
Something like that:
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 a user's password is required.
source to share