rails tutorials - toy_app

创建应用

1
2
rails new toy_app
cd toy_app

修改 Gemfile

1
2
3
4
5
6
7
8
9
10
...
group :development, :test do
gem 'sqlite3', '1.4.1'
gem 'byebug', '11.0.1', platforms: [:mri, :mingw, :x64_mingw]
end

group :production do
gem 'pg', '1.1.4'
end
...
1
2
# 安装gem时要指定--without production选项,禁止安装生产环境使用的gem 
bundle install --without production

使用 git 版本控制系统

1
2
3
4
5
6
git init
git add -A
git commit -m "Initialize repository"

git remote add origin https://github.com/<username>/toy_app.git
git push -u origin master

修改 root route

routes

app/controllers/application_controller.rb

1
2
3
4
5
class ApplicationController < ActionController::Base
def hello
render html: "hello, world!"
end
end

config/routes.rb

1
2
3
Rails.application.routes.draw do 
root 'application#hello'
end

创建数据资源

User model
microposts model
relation between user and micropost
1
2
rails generate scaffold User name:string email:string
rails generate scaffold Micropost content:text user_id:integer

修改根路由

config/routes.rb

1
2
3
4
Rails.application.routes.draw do 
resources :users
root 'users#index'
end

模型验证

app/models/micropost.rb

1
2
3
4
5
6
7
8
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length: { maximum: 140 }
end

class User < ApplicationRecord
has_many :microposts
end

数据库迁移

1
rails db:migrate

部署到heroku

1
2
3
4
5
6
git add -A
git commit -m "Finish toy app"
git push

heroku run rails db:migrate
git push heroku
Donate article here