Wednesday, March 17, 2021

Ruby on Rails quick start!

1) Create an application and run it!
rails new blog --skip-bundle
cd blog
bundle config set --local path 'vendor/bundle'
bundle install
rails webpacker:install
rails s

2) Create an API:

Add routes in config/routes.rb    
Rails.application.routes.draw do
  get 'users' => 'users#index'
end

Add a controller at app/controllers/users_controller.rb

class UsersController < ApplicationController
    def index
        render :json => 'Users Page'
    end
end

3) To render a template:

Create a html file in app/views/users/index.html.erb
<h1>Users Index</h1>

Modify app/controllers/users_controller.rb to render the template
class UsersController < ApplicationController
    def index
        render 'users/index'
    end
end


4) Connecting to database!

Modify config/database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  database: your_database_name
  pool: 5
  host: 127.0.0.1
  username: root
  password: 
  slave:
    host: 127.0.0.1 

development:
  <<: *default

Add the following line in Gemfile
gem 'mysql2'
Install this gem
bundle install
Add a users model and start the server

rails generate model user
rails s

Add a column in the migration file at db/migrate/xxxxx_create_users.rb

class CreateUsers < ActiveRecord::Migration[6.1]

  def change

    create_table :users do |t|

      t.string :name

      t.timestamps

    end

  end

end


In config/routes.rb add a route to list the users

Rails.application.routes.draw do

  get 'users/list' => 'users#list'

  get 'users' => 'users#index'

end


In app/controllers/users_controller.rb add the code to create and query from database

class UsersController < ApplicationController

    def index

        name = 'User ' + rand(1..10000).to_s

        User.create({:name => name})

        render 'users/index'

    end

    def list

        @users = User.all

        render 'users/list'

    end

end


Create a view to render the users in app/views/users/list.html.erb

<h1>Users</h1>


<ul>

  <% @users.each do |user| %>

    <li>

      <%= user.name %>

    </li>

  <% end %>

</ul>


Run migration and start the server

rails db:migrate

rails s


Open http://localhost:3000/users and refresh the page several times to create new users

Open http://localhost:3000/users/list to view the list of users created



Happy coding!







No comments:

Post a Comment