Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validates...multiple :on options?

Is it possible to have multiple entries for the :on option for the validates validation?

Something like the following:

class Library < ActiveRecord::Base

  validates :presence => true, :on => [:create, :update, :some_other_action]

end

Basically I would like to run one particular validation when multiple actions are called in the controller. For example, I would like to validate some user info on the create action, on a update action, and possibly some other actions as well.

Although I don't want the validation to run on all the methods.

Also, if there is an easier way of doing this, that would be great too!

Thanks in advance!

like image 699
schmudu Avatar asked Oct 30 '11 19:10

schmudu


4 Answers

Yes. Available in rails 4.1.

PR: https://github.com/rails/rails/pull/13754/files Official doc: http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate

Syntax: on: [:create, :custom_validation_context]

like image 72
Benjamin Crouzier Avatar answered Sep 21 '22 20:09

Benjamin Crouzier


Yes for create and update!

:on - Specifies when this validation is active. Runs in all validation contexts by default (nil), other options are :create and :update

However think of these values as database data create or update statements, and not rails controller actions. They may be doing similar things to data and the database, but they are different.
For example you may have another rails method that also updates the database, perhaps updating different fields, however the above ':update' will still account for that method even though it's not coming from a rails action with the name 'update'.

like image 34
Michael Durrant Avatar answered Sep 20 '22 20:09

Michael Durrant


This is not possible. Why? These :on events are NOT action names inside controller, but predefined ActiveRecord (MODEL) events, :create or :update or :save

There is no automatic connection between controller methods and model method.

like image 1
Petr Avatar answered Sep 20 '22 20:09

Petr


Had very similar issue, where I had to skip validation for certain controller actions, I tried the above ways but my problem was little different so they didn't work for me, so what I did is used attr_accessor and the unless configuration.

It will work for your cause smoothly.

in Model

validates :password, presence: true, unless: :skip_password_validation

attr_accessor :skip_password_validation

and when situation comes where I don't need the validation, I just make it true in controller

@user = User.find(params[:id])
@user.skip_password_validation = true 
like image 1
Faizaan Khan Avatar answered Sep 20 '22 20:09

Faizaan Khan