Rails, DEVISE - Preventing a user from changing their email address

后端 未结 3 1050
囚心锁ツ
囚心锁ツ 2021-01-15 06:29

When a user registers on my app they have to confirm their email, powered by Devise + Rails 3.

The email address defines the user\'s permissions so I don\'t want the

3条回答
  •  耶瑟儿~
    2021-01-15 07:15

    This is the perfect case for a custom validator. Since Rails3, they are much easier to do than before.

    class ImmutableValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        record.errors[attribute] << "cannot be changed after creation" if record.send("#{attribute}_changed?") && !record.new_record?
      end
    end
    
    class User < ActiveRecord::Base
      validates :email, :immutable => true
    end
    

提交回复
热议问题