user2911232
user2911232

Reputation:

Devise - hardcode certain usernames as already taken

I am trying to hardcode certain usernames which users will not be able to select during devise registration.

I didn't find any similar resource on the net and stackoverflow.

My attempt was to do this in users_controller.rb:

def create
  if @user.username == "someuser"
    flash.alert = "Username already taken"
    redirect_to new_user_registration_path
  end
end

which didn't work and I think its kind of odd to work anyway. Another unorthodox way is to check in applications_controller if the user "someuser" exists to immediately destroy him/her and redirect to signup.

Is there a proper way to do this and hardcode some users during registration?

Thank you.

Upvotes: 0

Views: 253

Answers (2)

Nitin Jain
Nitin Jain

Reputation: 3083

you should do that in model instead of controller

try something like this

validates_exclusion_of :username, in: %w( admin superuser ),
  message: "these username are reserved "

for more info http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_exclusion_of

Upvotes: 2

thorsten müller
thorsten müller

Reputation: 5651

This is in any case something that belongs to the model, not the controller. Most simple way would be to add this as a validation on username like this:

validates :username, exclusion: { in: %w(admin superuser) }

Upvotes: 1

Related Questions