Rails Guides 通知发布系统 CRUD 教程(基础版)

目标

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

1、确认操作环境

进入终端页面
ruby -v
rails -v

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 页面
[图片上传失败...(image-512f7b-1513996498024)]

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

通知页面

4、Routes

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

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

查看专案路由
rake routes
[图片上传失败...(image-3d6f61-1513996498025)]

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
[图片上传失败...(image-5981ec-1513996498025)]

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 页面
[图片上传失败...(image-9c8bda-1513996498025)]

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

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

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

  def create
    @notice = Notice.new(notice_params) #使用 “Notice 健壮参数”

    if @notice.save
      redirect_to notice_path @notice.id # 可以省略@notice.id,rails会自动解析重定向
    else
      render 'new' # 简写代码render :partial => "new"
    end
  end
  
  private
  
  def notice_params  # 设定 “Notice 健壮参数”
    params.require(:notice).permit(:title, :text)
  end
end

参考资料:
Render 與 Redirect_to 用法
Rails Guides 健壮参数

修改文件 app/views/notices/new.html.erb

<h1>New Notice</h1>
<%= form_for @notice do |f| %>
  <p>
    <%= f.label :title %> </br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %> </br>
    <%= f.text_field :text %>
  </p>

  <p>
    <%= f.submit 'save'%>
  </p>
<% end %>

刷新 http://localhost:3000/notices/new 页面
[图片上传失败...(image-fb701f-1513996498025)]
参考资料:
form_for使用总结

git add .
git commit -m "implement Notice#Create "

6、Read

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

class NoticesController < ApplicationController
* def create
  end
   
  def show
    @notice = Notice.find(params[:id]) #搜索 Notice 的 id
  end
end

新建文件 app/views/notices/show.html.erb

<h1>Show Notices</h1>
<p>
  <strong>Title:</strong>
  <%= @notice.title %>
</p>
<p>
  <strong>text:</strong>
  <%= @notice.text %>
</p>

打开 http://localhost:3000/notices/1 页面
[图片上传失败...(image-8c364c-1513996498025)]

git add .
git commit -m "implement implement Notice#Read"

7、添加数据验证

参考资料: Rails 入门 5.10添加验证
修改文件 app/models/notice.rb ,在 Model 层添加数据验证。

class Notice < ApplicationRecord
  validates :title, presence: true,      #标题不得为空
                  length: { minimum: 5 } # 标题最短5个字符
end

修改文件 app/views/notices/new.html.erb ,在 View 层实现 “验证失败” 的提示

#<h1>New Notice</h1>
#<%= form_for @notice do |f| %>
  <% if @notice.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@notice.errors.count, "error") %> prohibited
        this notice from being saved:
      </h2>
      <ul>
        <% @notice.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
* <p>
*   <%= f.label :title %> </br>

[图片上传失败...(image-c62725-1513996498025)]

git add .
git commit -m "add data validation"

8、Update

修改文件 app/controllers/notices_controller.rb 添加 def edit & def update

class NoticesController < ApplicationController
* def show
   
  def edit
    @notice = Notice.find(params[:id])
  end

  def update
    @notice = Notice.find(params[:id])

    if @notice.update(notice_params)
      redirect_to notice_path @notice.id # 可以省略@notice.id,rails会自动解析
    else
      render 'edit'
    end
  end
end

新建文件 app/views/notices/edit.html.erb

<h1>Edit Notice</h1>
<%= form_for @notice do |f| %>
  <% if @notice.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@notice.errors.count, "error") %> prohibited
        this notice from being saved:
      </h2>
      <ul>
        <% @notice.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <p>
    <%= f.label :title %> </br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %> </br>
    <%= f.text_field :text %>
  </p>

  <p>
    <%= f.submit 'save'%>
  </p>
<% end %>

打开 http://localhost:3000/notices/1/edit 页面
[图片上传失败...(image-2c4400-1513996498025)]

git add .
git commit -m "implement Notice#Update"

8.1、使用局部视图简化代码

参考资料:
Rails 入:5.12 使用局部视图去掉视图中的重复代码
Rails 布局和视图渲染

新建 app/views/notices/_form.html.erb

<%= form_for @notice do |f| %>
  <% if @notice.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@notice.errors.count, "error") %> prohibited
        this notice from being saved:
      </h2>
      <ul>
        <% @notice.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <p>
    <%= f.label :title %> </br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %> </br>
    <%= f.text_field :text %>
  </p>

  <p>
    <%= f.submit 'save'%>
  </p>
<% end %>

修改 app/views/notices/new.html.erb 为 下面的形式

<h1>New Notice</h1>

<%= render 'form' %>  <!-- 加载form局部视图 -->

<%= link_to 'Back', notices_path %>

修改 app/views/notices/edit.html.erb 为 下面的形式

<h1>Edit Notice</h1>

<%= render 'form' %>  <!-- 加载form局部视图 -->

<%= link_to 'Back', notices_path %>

git add .
git commit -m "add local page to new & edit html"

9、Index

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

class NoticesController < ApplicationController
  def index
    @notices = Notice.all
  end
  
* def show
end

新建文件 app/views/notices/index.html.erb

<h1>Listing Notices</h1>
</p>
<%= link_to 'New', new_notice_path %>  #发布新通知按钮
</p>

<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
  </tr>

  <% @notices.each do |notice| %>
    <tr>
      <td><%= notice.title %></td>
      <td><%= notice.text %></td>
      <td><%= link_to 'Show', notice_path(notice) %></td>
      <td><%= link_to 'Edit', edit_notice_path(notice) %></td>      
    </tr>
  <% end %>
</table>

git add .
git commit -m "implement Notice#index

10、Delete

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

class NoticesController < ApplicationController
* def update

  def destroy
    @notice = Notice.find(params[:id])
    @notice.destroy

    redirect_to notices_path
  end
end

修改文件 app/views/notices/index.html.erb

*     <td><%= link_to 'Show', notice_path(notice) %></td>
*     <td><%= link_to 'Edit', edit_notice_path(notice) %></td>
      <td><%= link_to 'Delete', notice_path(notice),
              method: :delete,
              data: { confirm: 'Are you sure' } %></td>

git add .
git commit -m "implement Noitce#Delete"

11、添加链接

在 show 页面最下方加入 Edit 链接

<%= link_to 'Edit', edit_notice_path %>

在 new、show、edit 页面最下方加入 Back 链接

<%= link_to 'Back', notices_path %>

[图片上传失败...(image-66345b-1513996498025)]

git add .
git commit -m "Add edit and back page links"

参考文章:

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容