开发者

Custom validation of associated model

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_nam开发者_如何转开发e 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜