Reputation: 11
Right now for my rails app (using devise and active admin), I am having user ids as serial numerals depending upon the serial of user id creation, i.e. first time I got user id 1, then again signed up with different details and then got user id 2 and then 3 and so on. But I want to have custom user ids, like greg51 or michel7as or something like that asked during user signup page How do I do it?
Upvotes: 1
Views: 773
Reputation: 101831
What you want is called vanity URLs where you let the users provide a more human friendly identifier for use in URLs. The column used is often called the slug column.
This is not a replacement for primary key ids, either in the form of an auto-incrementing integer column or UUIDs which is basically the same thing but it uses a random generated string instead to solve problems related to scalability. Primary keys are how your database tables refer to one another. Replacing it with a user generated value is possible but not a good idea at all.
To add a "username" feature in Devise you need to:
id
or username
column.id
or username
column.See:
Upvotes: 1
Reputation: 3005
If you want to login with a username or an email, just follow devise instructions in: https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address.
If you want to find a user using other fields you can @user.find_by(username: params[:username])
or whatever field you want in your controllers.
However, you should not change the id
for a new field (username, email or whatever). Rails generates an id
in all tables it creates and uses the id
as a primary key. The primary key should never be changed as it will be used in other tables as references. For this purpose, it uses a sequence field in the database, which creates unique integer values (it increments the last sequence value and returns it as the new id
) and guarantees that several transactions cannot get the same value (so no other record will have the same id
).
Besides the primary key, you can define many other unique fields, such as username, email, document_id, etc. Although these fields can also be unique (and can be forced to be unique using a database constraint and the validates uniqueness
in rails, they are not used as primary key (so you can change them later and no references will be affected).
Upvotes: 2
Reputation: 6870
Add a field to your user model:
rails g migraton AddUsernamaToUser username:string
Then add a field to your devise form:
https://github.com/plataformatec/devise/issues/4201
And you'll be able to ask for a username.
Upvotes: -1