Calling custom validation methods in Rails

I just upgraded my rails to 2.3.4, and I noticed this with checks: Suppose I have a simple company model that has a name. nothing for this. I want to do my own check:

class Company < ActiveRecord::Base validate :something def something false end end 

Saving the model really works in this case. The same thing happens if I override validate () and return false. I noticed this in a more complex model, where my check returned false, but the object was still persisting ... I tried this in an essentially empty model and applied the same. Do I have a new practice? This is not like some of my old rails rules.

+55
validation ruby-on-rails
Oct 23 '09 at 7:36
source share
3 answers

Your checks are performed using the validate method. However, the rails do not rely on the return value.

It depends on the presence of verification errors or not. Therefore, you should add errors when your model does not validate.

 def something errors.add(:field, 'error message') end 

Or, if the error is not related to the field:

 def something errors.add(:base, 'error message') end 

Then your model will not be saved, because there are errors.

+107
Oct 23 '09 at 7:47
source share

You get confusion between validations and callbacks.

The checks should fail if there are any errors in the object, it does not matter if the confirmation returns. Callbacks fail if they return false, regardless of whether they added any errors to the object.

Does Rails use valid calls? from saving calls that don’t check the result of any checks.

Edit: Rails treats validate :method as a callback, but valid? still does not check their results, only for errors that they added to the object.

I do not think that this behavior has changed at all, but I could be wrong. I don't think I ever wrote a confirmation to return false before.

+14
Oct 23 '09 at 7:47
source share

Only FYI errors.add_to_base('error message') deprecated in rails 3 and received a replacement for

 errors[:base] << "Error message" 

or

 errors.add(:base, "Error message") 
+8
Jun 08 '13 at 22:14
source share



All Articles