Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Custom validation message

I'm trying to make a simple custom validation message. The validation I'm using compiles and runs fine, but I don't see any change in the message:

validates :rating, :inclusion => { :in => 0..5 }, :presence => { :message => " must be within 0-5" }

The message I get is still Rating is not included in the list

I need to validate that rating is present and is a decimal between 0-5

like image 307
Ankit Soni Avatar asked Aug 06 '11 10:08

Ankit Soni


People also ask

How does validation work in Rails?

Before saving an Active Record object, Rails runs your validations. If these validations produce any errors, Rails does not save the object. After Active Record has performed validations, any errors found can be accessed through the errors instance method, which returns a collection of errors.

What is Validates_presence_of?

validates_presence_of(*attr_names) public. Validates that the specified attributes are not blank (as defined by Object#blank?), and, if the attribute is an association, that the associated object is not marked for destruction. Happens by default on save.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

Alright, I solved it. This is the validation that works:

validates :rating, :inclusion => { :in => 0..5, :message => " should be between 0 to 5" }
validates :rating, :presence => { :message => " cannot be blank" }

and I added this

validates :rating, :numericality => { :message => " should be a number" }

like image 135
Ankit Soni Avatar answered Sep 28 '22 07:09

Ankit Soni