Skip to content

# Step 06 — Axios User Model and Controller Setup

Gerald Goh edited this page Sep 8, 2020 · 2 revisions

Axios Setup

A client HTTP API based on the XMLHttpRequest interface provided by browsers.

$ npm install axios

+ axios@0.19.2
added 135 packages from 85 contributors, removed 452 packages, updated 1128 packages and audited 14644 packages in 162.531s

53 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

User Model Setup

Create a user model and controller. The user model will represent the database table that will hold information about the user while the controller will receive and handle requests to create, and read readings. When a user requests a user, the user controller receives this request and passes it to the user model, which retrieves the requested data from the database. The model then returns the user data as a response to the controller. Finally, this information is displayed in the browser.

Start by creating a user model by using the generate model sub command provided by Rails and by specifying the name of the model along with its columns and data types.

Build a User model and migrate it to the database.

User preference includes

  1. Monthly purchased units (i.e. 1800, 2100, 2400, 2700, 3000)
  2. Monthly target saving (i.e. 5%, 10%, 15%, 20%)
$ rails generate model User name email password:digest units:integer target:integer
      invoke  active_record
      create    db/migrate/20200430210731_create_users.rb
      create    app/models/user.rb
      create    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      create      test/fixtures/users.yml

Edit user model file

app/models/user.rb

class User < ApplicationRecord
  has_secure_password
  validates :name, presence: true, length: { minimum: 3, maximum: 100 }
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: true
  validates :units, presence: true
  validates :target, presence: true
end
$ rails db:migrate
== 20200430210731 CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.1482s
== 20200430210731 CreateUsers: migrated (0.1488s) =============================

Other useful Rails DB Commands

rails db:drop
Dropped database 'energy_tracker_development'
Dropped database 'energy_tracker_test'

$ rails db:create
Created database 'energy_tracker_development'
Created database 'energy_tracker_test'

$ rails db:reset
Dropped database 'energy_tracker_development'
Dropped database 'energy_tracker_test'
Created database 'energy_tracker_development'
Created database 'energy_tracker_test'

Generate users controller

$ rails generate controller api/v1/users index create show -j=false -y=false --skip-template-engine --no-helper
      create  app/controllers/users_controller.rb
      create  erb
      create   app/views/users
      create  test_unit
      create  test/controllers/users_controller_test.rb
      create  helper

In this command, you created a Users controller in an api/v1 directory with an index, create, and show action. The index action will handle fetching all your users, the create action will be responsible for creating new users and the show action will fetch a single user.

You also passed some flags to make the controller more lightweight, including:

-j=false which instructs Rails to skip generating associated JavaScript files. -y=false which instructs Rails to skip generating associated stylesheet files. --skip-template-engine, which instructs Rails to skip generating Rails view files, since React is handling your front-end needs. --no-helper, which instructs Rails to skip generating a helper file for your controller.

Add methods

  1. Create action, you use ActiveRecord’s create method to create a new user.
  2. Add token verification
  3. Add API methods
  4. A private method where you whitelisted your controller parameters to prevent wrong or malicious content from getting into your database.
app/controllers/v1/users_controller.rb

class Api::V1::UsersController < ApplicationController

  def create
    @user = User.new(
      name: params[:name],
      email: params[:email],
      password: params[:password],
      password_confirmation: params[:password_confirmation],
      units: params[:units],
      target: params[:target],
    )
    if @user.save
      render json: {
        code: 200
      }
    else
      render json: {
        code: 400,
        errors: @user.errors.messages
      }
    end
  end

  def index
    @users = User.all
    if @users
      render json: {
        code: 200,
        data: User.all.as_json
      }
    else
      render json: @users.errors
    end
  end

  def find_user
    @users = User.all
    @users = User.find(params[:id])
    if @users
      render json: {
        code: 200,
        data: @users.as_json
      }
    else
      render json: @users.errors
    end
  end

  def destroy; end
end

Add routes

/config/routes.rb

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      post 'users', to: 'users#create'
      get 'users', to: 'users#index'
      get 'users/:id', to: 'users#find_user'
      get 'users/destroy'
    end
  end
  root 'homepage#index'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end