Adding Phone Number to User Model
Apologies if this question is too general. I'm relatively new to Rails and development in general. I am creating a Rails app that uses Twilio for SMS verification. Users sign up for the app using their name and phone number. That phone number then gets verified by a pin delivered via SMS. I am having a tough time figuring out whether it would be easier and/or better to use a phone_number model and then create an association between users and phone_numbers using belongs_to: and has_one: or if I can make the phone number a part of the User model.
I am using Rails 4.2.1
Here is my User model:
class User < ActiveRecord::Base has_secure_password validates_presence_of :name validates_presence_of :phone_number validates_uniqueness_of :phone_number end
class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to root_url, notice: "Saved" else render 'new' end end private def user_params params.require(:user).permit(:name, :phone_number, :password, :password_confirmation) end end
This is the Twilio tutorial I've been attempting to follow:
Am I overthinking this? Is a user really just a phone_number with a name?
If I do wind up having to create a phone number model/controller, how will I modify my routes? And how would that change my sign up page, which right now includes this:
<div class="field"> <%= f.label :phone_number %><br /> <%= f.text_field :phone_number %> </div>
You can make the phone_number model as part of the user and just use the [:user][:phone_number] parameter to create it. It is really up to you and what kind of user experience you are trying to build.
Does the user needs to verify his/her phone number during registration? Does the user has to do it after creating an account?
In the first case, you can make the phone number a separate model which belongs to the user. You put all the methods for the Twilio integration in the phone_number model and use them in the users_controller. You can make the verification step simpler by avoiding AJAX and putting it as a next step of the user registration.
Here's how it might look like:
In your model:
class PhoneNumber < ActiveRecord::Base belongs_to :user ... end
In your user controller:
def create @user = User.new(permitted_params) @phone_number = PhoneNumber.find_or_create_by(user_id: @user.id ,phone_number: params[:user][:phone_number]) @phone_number.generate_pin @phone_number.send_pin ... end