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 templateclass 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 Gemfilegem 'mysql2'
Install this gembundle install
Add a users model and start the serverrails generate model user
rails s
Add a column in the migration file at db/migrate/xxxxx_create_users.rbclass 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 usersRails.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 databaseclass 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 serverrails db:migrate
rails s
No comments:
Post a Comment