Rails Guides 通知发布系统 CRUD 教程(改进版)

目标

建立一个可以发布,更新,删除的通知系统,通知由标题与正文构成。

1、确认操作环境

进入终端页面

$ ruby -v
#=> ruby 2.3.1p112
$ rails -v
#=> Rails 5.1.4

git status  # 查看 git 状态
rake routes # 查看路由

2、建立新 rails 专案

rails new rails001
cd rails001
git init
git add .
git commit -m "First Commit"

3、建立 Welcome 页面

git checkout -b ch01

在文件 config/routes.rb 添加 welcome 页面路由

Rails.application.routes.draw do
  root 'welcome#index' # 确定首页路由
end

新建文件 app/controllers/welcome_controller.rb

class WelcomeController < ApplicationController
  def index
  end
end

新建文件夹 app/views/welcome
新建文件 app/views/welcome/index.html.erb

<h1>Hello World</h1>

再开一个终端页面,执行 rails s
打开 http://localhost:3000 页面

git add .
git commit -m "implement welcome#html"

通知页面

4、Routes

在文件 config/routes.rb 添加 notices 路由

* root 'welcome#index'
  resources :notices # 资源使用复数名词

查看专案路由
rake routes

4.1 Models

在建立数据库建立 Noitce 数据表(表名使用单数)
rails g migration notice

打开新生成文件 db/migrate/xxxx一堆数字xxxx_notice.rb

class Notice < ActiveRecord::Migration[5.0]
* def change
    create_table :notices do |t|
      t.string :title
      t.text   :text

      t.timestamps
    end
* end
end

rake db:create
rake db:migrate
重启 rails s

新建文件 app/models/notice.rb (Model)

class Notice < ApplicationRecord
end

进入 rails c
Notice
u = Notice.create(title: "Hello", text: "World")
Notice.all
exit

5、Create

新建文件 app/controllers/notices_controller.rb (表名使用单数)添加 def new

class NoticesController < ApplicationController
  def new
  end
end

新建文件夹 app/views/notices
新建文件 app/views/notices/new.html.erb

<h1>New Notice</h1>

打开 http://localhost:3000/notices/new 页面

现在,已经建立了 def new 方法对应的最基本静态页面,接下来完善动态动作与基本前端页面

修改文件 app/controllers/notices_controller.rb 修改 def new添加 def create

class NoticesController < ApplicationController
  def new
    @notice = Notice.new
  end

  def create
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值