Custom Rails Validation not adding 'field_with

2019-05-25 03:59发布

I'm working on a Rails 4 site with a form that needed some custom validation. But when the validation criteria fails and the error message is shown, the input fields I'm checking aren't given the field_with_errors wrapper. All other fields being validated are getting the wrapper properly, but their validation is a simple presence check on each attribute.

How can I have the wrapper added in with my custom validation?

Additional notes: I'd like to only show my error message once, if possible - but highlight both fields.

In my model:

validate :at_least_one_apply_method

def at_least_one_apply_method
  if [self.apply_url, self.application_instructions].reject(&:blank?).size == 0
    errors[:base] << ("Please provide at least one: Where to Apply or Applications Instructions.")
  end
end 

Let me know of any other information needed. Thank you!

2条回答
女痞
2楼-- · 2019-05-25 04:54

You are adding the custom error message to errors[:base]. You need to add it to the field which you want to be wrapped e.g.

errors[:apply_url] << ("Please provide at least one: Where to Apply or Applications Instructions.")
errors[: application_instructions] << ("Please provide at least one: Where to Apply or Applications Instructions.")
查看更多
何必那么认真
3楼-- · 2019-05-25 05:01

Errors message are only bind to filed if object.errors hash have key of that field name. But you are adding custom message with the key of base.

So you can do like below

validate :at_least_one_apply_method

def at_least_one_apply_method
  [self.apply_url, self.application_instructions].map{|field| field.blank? ? (self.errors.add("field","Please provide at least one: Where to Apply or Applications Instructions.")
  ") : ''}
end 
查看更多
登录 后发表回答