赵龙 全栈之路

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

| Comments

目标

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

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 页面路由

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

新建文件 app/controllers/welcome_controller.rb

app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
  def index
  end
end

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

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 路由

config/routes.rb
* root 'welcome#index'
  resources :notices # 资源使用复数名词

查看专案路由
rake routes

4.1 Models

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

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

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)

app/models/notice.rb
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

app/controllers/notices_controller.rb
class NoticesController < ApplicationController
  def new
  end
end

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

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

app/controllers/notices_controller.rb
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.idrails会自动解析重定向
    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

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 页面


参考资料:
form_for使用总结

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

6、Read

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

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

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

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 页面

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

7、添加数据验证

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

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

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

app/models/notice.rb
#<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>

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

8、Update

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

app/controllers/notices_controller.rb
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.idrails会自动解析
    else
      render 'edit'
    end
  end
end

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

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 页面

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

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

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

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

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 为 下面的形式

app/views/notices/new.html.erb
<h1>New Notice</h1>

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

<%= link_to 'Back', notices_path %>

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

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

app/controllers/notices_controller.rb
class NoticesController < ApplicationController
  def index
    @notices = Notice.all
  end
  
* def show
end

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

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

app/controllers/notices_controller.rb
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

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 %>

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

参考文章:

Comments

comments powered by Disqus