简体   繁体   中英

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!

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]

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'.

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM