rails ActiveRecord validation on specific controller and action

前端 未结 3 1088
天涯浪人
天涯浪人 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条回答
  •  春和景丽
    2021-02-06 09:40

    Just a tip for implementing @markets' answer

    We can use

      with_options if: :validate_email? do |z|
        z.validates :email, presence: true
        z.validates :name, presence: true
      end
    

    for multiple validations on our specific action.

    Also, we use session to pass a variable which indicate params from this action will need some validations

    Controller:

      before_action :no_validate, only: [:first_action, :second_action, ..]
      before_action :action_based_validation, only: [:first_action, :second_action, ..]
    
    
      def first_action; end
      def second_action; end
    
      def update
        ..
        @instance.validate = session[:validate]
        ..
        if @instance.update(instance_params)
          ..
        end
      end
    
    
      private
    
        def no_validate
          session[:validate] = nil
        end
    
        def action_based_validation
          # action_name in first_action will = "first_action"
          session[:validate] = action_name
        end
    

    Model

      attr_accessor :validate
    
      with_options if: "validate == 'first_action'" do |z|
        z.validates :email, presence: true
        ..more validations..
      end
    
      with_options if: "validate == 'second_action'" do |z|
        z.validates :name, presence: true
        ..more validations..
      end
    

    more details: http://guides.rubyonrails.org/active_record_validations.html#conditional-validation

提交回复
热议问题