how would I validate this?

Hi all,

My User model has_many :phone_numbers . For one form, I need to validate that at least two phone (out of three possible) numbers have been entered, and that the phone numbers are formed well. Also, if there's an error with the form the phone numbers need to be filled in when the page refreshes. What's the DRYest way to do this?

Thanks! Daniel

My User model has_many :phone_numbers . For one form, I need to validate that at least two phone (out of three possible) numbers have been entered, and that the phone numbers are formed well. Also, if there's an error with the form the phone numbers need to be filled in when the page refreshes. What's the DRYest way to do this?

Create a before_save method to run the checks? If it fails, set the errors and return false...

-philip

Perhaps it'd be better to actually include the code. In my controller I have:

if request.post?   params[:profile]   @profile = current_user   valid = @profile.update_attributes(params[:profile])

  %w{@phone_1 @phone_2 @phone_3}.each do |name|     phone_number_params = params[name[1..7]]     if(phone_number_params)       self.instance_variable_set(name, PhoneNumber.new(phone_number_params))       valid = (@profile.phone_numbers << self.instance_variable_get(name)) && valid     end   end

  if valid     do_something   end end

@profile ||= current_user %w{@phone_1 @phone_2 @phone_3}.each do |name   self.instance_variable_set(name, (self.instance_variable_get(name) ||     PhoneNumber.new)) end