《Ruby on Rails 教程》第 2 章

247 阅读1分钟

规划应用

创建启动项目 hello_web_app

rails new hello_web_app --database=mysql
cd hello_web_app
bundle install --without production
bin/rails s

Mac 上解决安装 mysql2 的问题:github.com/brianmario/…
Mac 上解决 SSL connection error 问题:stackoverflow.com/questions/6…

在 Application 控制器中添加 hello 动作,app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  def hello
    render html: "hello rails"
  end
end

设置根路由,config/routes.rb

Rails.application.routes.draw do
  root "application#hello"
end

打开 http://127.0.0.1:3000 显示 hello rails

Users 资源

bin/rails generate scaffold User name:string email:string
bin/rails db:migrate
bin/rails s

使用脚手架生成 Users 资源时生成了很多用来处理用户的页面

启动项目后可看见关于 User 的页面

Micropost 资源

bin/rails generate scaffold Micropost content:text user_id:integer
bin/rails db:migrate
bin/rails s

同上,创建了一系列关于 Micropost 的页面

编辑 app/models/micropost.rb,限制 post 的长度

class Micropost < ApplicationRecord
  validates :content, length: { maximum: 140 }
end

编辑 app/models/user.rb,让一个用户拥有多篇 post,name 和 email 必须填写

class User < ApplicationRecord
  has_many :microposts
  validates :name, presence: true
  validates :email, presence: true
end

编辑 app/models/micropost.rb,一篇 post 属于一个用户,post 必须填写

class Micropost < ApplicationRecord
  belongs_to :user
  validates :content, length: { maximum: 140 }, presence: true
end

代码:gitee.com/huzhengen/s…