Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Validation in Rails to test if a number can be nil or some positive integer

how to validate a model with one integer property say customer_id in order table which allows customer_id but if its available it should be great then 0

class Order < ActiveRecord::Base
  validates :name, presence: true, length: {minimum: 3, maximum: 10}
  validates :customer_id,  numericality: {greater_than_or_equal_to: 1}, presence: false
end

i did it using above but it is not accepting null values in number.

like image 579
rajansoft1 Avatar asked Mar 04 '14 09:03

rajansoft1


People also ask

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.


1 Answers

You need to add allow_nil: true.

http://guides.rubyonrails.org/active_record_validations.html#allow-nil

like image 175
sevenseacat Avatar answered Sep 28 '22 09:09

sevenseacat