validate and update single attribute rails

后端 未结 5 1463
旧巷少年郎
旧巷少年郎 2021-02-08 22:55

I have the following in my user model

attr_accessible :avatar, :email

validates_presence_of :email
has_attached_file :avatar # paperclip

validates_attachment_s         


        
5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-08 23:25

    Here is my solution. It keeps the same behaviour than .valid? method, witch returns true or false, and add errors on the model on witch it was called.

    class MyModel < ActiveRecord::Base
      def valid_attributes?(attributes)
        mock = self.class.new(self.attributes)
        mock.valid?
        mock.errors.to_hash.select { |attribute| attributes.include? attribute }.each do |error_key, error_messages|
          error_messages.each do |error_message|
            self.errors.add(error_key, error_message)
          end
        end
    
        self.errors.to_hash.empty?
      end
    end
    
    > my_model.valid_attributes? [:first_name, :email] # => returns true if first_name and email is valid, returns false if at least one is not valid
    > my_modal.errors.messages # => now contain errors of the previous validation
    {'first_name' => ["can't be blank"]}
    

提交回复
热议问题