All threads / How do i use a username instead of an email?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do i use a username instead of an email?

Ookma-Kyi asked in Rails

I am watching the series and really enjoying it. I am up to Part 11 where you create the user model. Is there a way to use a username instead of email?

Hey Ookma-Kyi

Yes you can, you just need to add a user name column to your users model with a migration:
add_column :users, :user_name, :string

In your user model make sure you add a validation so it is present and unique:

validates :user_name, presence: true, uniqueness: true

In your signup form make sure you add a user_name field:

<%= f.text_field :user_name %>

And then when the user signs in, in your create session controller action search for the user by user_name rather than email:

User.find_by(user_name: params[:user][:user_name])

Hope that helps!

Thanks OP for your reply. I also would like to know more how to add username instead of an email.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 53,130+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.