views:

30

answers:

1

Hello,

I have provider and patient models which both are belongs_to contact. On the provider and patient edit forms i use fields_for :contact to render associated contact fields.

The problem is in that i want to use different validation rules for provider.contact and patient.contact objects, i.e. i want to validate presence of contact's first_name in patient edit form, but i don't want to validate presence of first_name in provider edit form.

I tried to add dynamic validation rule in patient model:

validate :contact_first_name_blank

def contact_first_name_blank
  errors.add('contact[first_name]', 'can not be blank') if contact.first_name.blank?
end

It adds error message in case of empty first_name field, but it does not hightlights contact[first_name] field.

Please help me resolve this problem, may be there is better way to do such validations.

+2  A: 

You're adding errors to the wrong model. The square-bracket notation is only used for naming HTML form elements, not the error structure, which is specified by attribute name as far as I know.

validate :contact_first_name_blank

def contact_first_name_blank
  if (contact.first_name.blank?)
    errors.add_to_base('Contact first name can not be blank') 
    contact.errors.add('first_name', 'can not be blank')
  end
end

The fields_for call checks for errors on the object passed to it, not any parent objects, as it is unaware of those relationships.

tadman
Thank you, that completely resolves my problem.
akhkharu
You should give him the checkmark (click the outline of a checkmark) if it is the "correct" or "accepted" answer.
jamuraa
Got it, thanks.
akhkharu