Rails, DEVISE - Preventing a user from changing their email address
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 user to be able to change it once registered. so removed :email from the users.rb attr_accessible which worked for a logged in user, but now user's can't register.
What's the right way to handle this? So users can't update their开发者_如何学运维 email but can register with their email using devise.
Thanks
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
attr_readonly :email
That solved the problem easily.
https://groups.google.com/forum/#!topic/plataformatec-devise/skCarCHr0p8
I would personally leave the attr_accessible for :email and just remove the email field from the edit view. Also, you will want to strip out any email param from the params hash in the update action.
精彩评论