AnApprentice
AnApprentice

Reputation: 111080

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

Upvotes: 3

Views: 2314

Answers (3)

ademola osindero
ademola osindero

Reputation: 21

attr_readonly :email

That solved the problem easily.

https://groups.google.com/forum/#!topic/plataformatec-devise/skCarCHr0p8

Upvotes: 2

Adam Lassek
Adam Lassek

Reputation: 35515

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

Upvotes: 5

raid5ive
raid5ive

Reputation: 6642

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.

Upvotes: 0

Related Questions