简体   繁体   中英

Validate the presence of one of two fields when one might be zero

I just came across a situation where the accepted solution for Validate presence of field only if another field is blank - Rails wasn't complete.

I'd like one or both of two fields to be present but in my case one of the fields points needs to be a number between 0 and 10. In cases where the points field is zero :points? is evaluating to false and a blank comment is considered invalid. I tried to make it a little more specific by specifying :points.blank? :

validates :comment, presence: { unless: :points.blank?, on: :create }
validates :points, presence: { unless: :comment?, on: :create }, 
                   numericality: { only_integer: true, allow_nil: true, less_than_or_equal_to: 10, greater_than_or_equal_to: 0 }

That seems to work (I can save the first entry with 0 points and no comment) but on subsequent saves I'm getting weird errors from the controller:

NoMethodError (undefined method 'validate' for false:FalseClass): app/controllers/comments_controller.rb:8:in 'create'

Is there something else I need to do with the validation? Do I need to use a lambda (as suggested in some answers to the linked question)?

:points.blank? evaluates to false , which is being set as the value of the :unless key in your hash. You will need to specify a method name or Proc for the :unless option to work. You can simplify the whole setup:

validates :comment, presence: true, on: :create, if: :points?
validates :points, numericality: :only_integer, inclusion: 0..10

Not sure how you got first record working, but this is not correct syntax:

validates :comment, presence: { unless: :points.blank?, on: :create }

Instead you should be defining a method like this in your model:

def points_blank?
  # your code for zero handling
  # 
end

and then use that method in unless like this:

validates :comment, presence: { unless: :points_blank?, on: :create }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM