Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add errors to an ActiveRecord object without associating them with a particular attribute?

Tags:

If you need to code a considerably complex validation, the error sometimes doesnt lie in a particular attribute, but in a combination of several of them.

For example, if i want to validate that a the time period between :start_date and :end_date doesnt contain any sunday, the error doesnt belong specifically to either of those fields, but the Errors add method requires to specify it.

like image 638
agente_secreto Avatar asked May 30 '12 14:05

agente_secreto


People also ask

How do I bypass validation?

A very common way to skip validation is by keeping the value for immediate attribute as 'true' for the UIComponents. Immediate attribute allow processing of components to move up to the Apply Request Values phase of the lifecycle. scenario: While canceling a specific action, system should not perform the validation.

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.

What is Activerecord in Ruby on Rails?

1 What is Active Record? 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.

How does validation work in Rails?

Rails built-in Validation MethodsValidates whether associated objects are all valid themselves. Work with any kind of association. It validates whether a user has entered matching information like password or email in second entry field. Validates each attribute against a block.


2 Answers

Try doing something like this:

# Your Model.rb validate :my_own_validation_method  ...  private  def my_own_validation_method     if there_is_no_sunday_in_the_range         self.errors[:base] << "You must have a Sunday in the time range!"     end end 

Basically, you can add your own complex validations to a model, and when you see that something erroneous has happened, you can add an error string in the array of errors.

like image 69
MrDanA Avatar answered Dec 13 '22 10:12

MrDanA


model_instance.errors[:base] << "msg" 
like image 35
Viktor Trón Avatar answered Dec 13 '22 09:12

Viktor Trón