rails ActiveRecord validation on specific controller and action

前端 未结 3 1077
天涯浪人
天涯浪人 2021-02-06 09:09

is it possible to run ActiveRecord validates on given controller and action.

For example I have user_controller and signup_controller

I

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 09:39

    You can run validations using an if conditional:

    validates :email, presence: true, if: :validate_email?
    

    Now you need to define this instance method (in your model):

    def validate_email?
      validate_email == 'true' || validate_email == true
    end
    

    This validate_email attribute could be a virtual attribute in your model:

    attr_accessor :validate_email
    

    And now, you can perform email validation depending on that virtual attribute. For example, in signup_controller#create you can do something like:

    def create
      ...
    
      @user.validate_email = true
      @user.save
    
      ...
    end
    

提交回复
热议问题