rails101再复盘-加深记忆-1

2.2 开始

配置好基础,新建项目
rails new rails101
cd rails101
git init
git add .
git commit -m "git init"

2.3 套上 bootstrap

修改 Gemfile,在 group :development, :test do前一行加入 gem 'bootstrap-sass'
然后终端安装 bundle install

接着,将 Bootstrap 的 CSS 套件装进项目里面:

mv app/assets/stylesheets/application.css app/assets/stylesheets/application.scss

最后添加2个@魔法,并git 保存

# app/assets/stylesheets/application.scss
/*
 * ...(一堆注解)
 *= require_tree .
 *= require_self
 */

@import "bootstrap-sprockets";
@import "bootstrap";

2.4 套用 Bootstrap 的 html 样式 (以下内容无需记忆)

上一节只是“挂上”Bootstrap 使用的 CSS
这一节则是让全站的 HTML 架构,套用 Bootstrap 的制服

新增文件夹 mkdir app/views/common 新增touch app/views/common/_navbar.html.erb 填入

<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="/">Rails 101</a>
        </div>

        <div class="collapse navbar-collapse">
            <ul class="nav navbar-nav navbar-right">
                <li>
                    <%= link_to("登录", '#') %>
                </li>
            </ul>
        </div>
    </div>
</nav>

新增 touch app/views/common/_footer.html.erb

<footer class="container" style="margin-top: 100px;">
    <p class="text-center">Copyright ©2017 Rails101
        <br>Design by
        <a href="http://courses.growthschool.com/courses/rails-101/" target=_new>xdite</a>
    </p>
</footer>

修改全域 HTML 样式 application.html.erb

# app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
    <head>
        <title>Rails101</title>
        <%= csrf_meta_tags %>

        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
        <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    </head>

    <body>

        <div class="container-fluid">
            <%= render "common/navbar" %>
            <%= yield %>
        </div>

        <%= render "common/footer" %>

    </body>
</html>

产生一个新的空 Hello World 页面 (放在 welcome#index)

  • 新增一个 welcome controller
    rails g controller welcome
  • 新增一个空的 HelloWorld 页面
    touch app/views/welcome/index.html.erb
    填入
<h1> Hello World! </h1>

将首页指到 welcome 下的 index.html.erb 页面

# config/routes.rb
Rails.application.routes.draw do
  root 'welcome#index'
end

最后,我们先git保存,再 rails s ,就能看到最简单的hello world 最简web页面了😄

2-5 制作漂亮的“提示信息” (以下内容无需记忆)

  • 将 Bootstrap 的 js 提示套件 bootstrap/alert “挂”进项目里面
    require_tree 上加入 //= require bootstrap/alert
# app/assets/javascripts/application.js
... (一堆注解)
//= require jquery
//= require jquery_ujs
//= require turbolinks
+//= require bootstrap/alert
//= require_tree .
  • 新增 app/views/common/_flashes.html.erb
# app/views/common/_flashes.html.erb
<% if flash.any? %>
  <% user_facing_flashes.each do |key, value| %>
    <div class="alert alert-dismissable alert-<%= flash_class(key) %>">
      <button class="close" data-dismiss="alert">×</button>
      <%= value %>
    </div>
  <% end %>
<% end %>
  • 加入 app/helpers/flashes_helper.rb
# app/helpers/flashes_helper.rb
module FlashesHelper
  FLASH_CLASSES = { alert: "danger", notice: "success", warning: "warning"}.freeze

  def flash_class(key)
    FLASH_CLASSES.fetch key.to_sym, key
  end

  def user_facing_flashes
    flash.to_hash.slice "alert", "notice", "warning" 
  end
end
  • application.html.erb 内加入 flash 这个 partial
    <%= yield %> 前加入 <%= render "common/flashes" %>
# app/views/layouts/application.html.erb
  <%= render "common/flashes" %>
  <%= yield %>
  • git 存档并测试
    修改 app/controllers/welcome_controller.rb。加入 flash[:notice] = "早安!你好!"。你应该可以看到系统跳出“绿色”提示窗
# app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
  def index
    flash[:notice] = "早安!你好!"   # alert 红色,warning 黄色
  end
end




3-1 建立讨论群的架构

这一章,我们要带大家设计出一个讨论群“列表”。我们会完成以下事项:
讨论群要有“标题”与“叙述”
使用者要可以看到“讨论群一览表”

  • git checkout -b ch02 切换新分支,代码出错还可以悔改

  • 设计 Group 的 model 架构
    为了做到在讨论群要有“标题”与“叙述”,我们在这里要建立一个 model Group,并建立数据表 group 的两个栏位 :
    title (string 字串属性)
    description (text 文字属性)
    所以终端输入: rails g model group title:string description:text
    将数据库建立起来,并执行 rake db:migrate

  • 产生 groups controller
    rails g controller groups

  • 建立 index action 以及 index 的 view

# 修改 app/controllers/groups_controller.rb
class GroupsController < ApplicationController
  def index
    @groups = Group.all
  end
end

touch app/views/groups/index.html.erb

# app/views/groups/index.html.erb
<div class="col-md-12">
  <div class="group">
    <%= link_to("New group", new_group_path, class: "btn btn-primary pull-right") %>
  </div>
  <table class="table table-hover">
    <thead>
      <tr>
        <td>#</td>
        <td>Title</td>
        <td>Description</td>
      </tr>
    </thead>
    <tbody>
      <% @groups.each do |group| %>
        <tr>
          <td>#</td>
          <td><%= link_to(group.title, group_path(group)) %></td>
          <td><%= group.description %></td>
          <td>
              <%= link_to("Edit", edit_group_path(group), class: "btn btn-sm btn-default")%>
              <%= link_to("Delete", group_path(group),    class: "btn btn-sm btn-default", 
                          method: :delete, data: { confirm: "Are you sure?" } )%>
          </td>
        </tr>
      <% end %>
    </tbody>
  </table>
</div>
  • 在 routing 上挂上 groups
    在 root 'welcome#index' 前加上一行 resources :groups
# config/routes.rb
Rails.application.routes.draw do
   resources :groups
   root 'welcome#index'
end
  • 添加一些数据, 先终端rails console,再输入
    Group.create(title: "Board 1", description: "Board 1 body")
    Group.create(title: "Board 2", description: "Board 2 body")

再重新打开 http://localhost:3000/groups 可以看到成果了,图略

  • 最后记得 git

3-2 将首页换成讨论群一览表

  • 修改 routing
# config/routes.rb
Rails.application.routes.draw do
  resources :groups
+  root 'groups#index'
-  root 'welcome#index'
end

然后你就可以在 http://localhost:3000/ 看到 Group 一览表了,最后一步,还是 git




4-1 手动实作讨论群的“新增”“修改”“删除”功能

实作看板的“新增” new / create
实作看板的“编辑” edit / update
实作看板的“删除” destroy
使用 gem "simple_form" 产生表单
限制看板标题“不得为空”

4-2 实作讨论群“新增”功能

这里,我先写出 controller 的全部代码,之后的都是补充 views界面

# CRUD 作为基础应该提前写出来,后面不会再重复
def show
  @group = Group.find(params[:id])
 # @posts = @group.posts   # 后面会涉及的代码,这里忽略
end

def index
  @groups = Group.all
end

def new
  @group = Group.new
end

def create
  @group = Group.new(group_params)
#  @group.user = current_user   # 这些是后面涉及的
  if @group.save

    redirect_to groups_path
  else
    render :new
  end
end

def edit
  @group = Group.find(params[:id])
end

def update
  @group = Group.find(params[:id])
  if @group.update(group_params)
    redirect_to groups_path, notice: "update success"
  else
    render :edit
  end
end

def destroy
  @group = Group.find(params[:id])
  @group.destroy
  redirect_to groups_path, alert: "deleted ,say bye"
end

private

def group_params
  params.require(:group).permit(:title, :description)
end

end
    1. git checkout -b ch03新建分支
    1. 建立 new action 略
    1. 建立 new action 的表单
      touch app/views/groups/new.html.erb
<div class="col-md-4 col-md-offset-4">
    <h2>新增讨论版</h2>

    <hr>
    <%= form_for @group do |f| %>

    标题
    <%= f.text_field :title %>
    <br>
    叙述
    <br>
    <%= f.text_area :description %>
    <br>

    <%= f.submit "Submit", :disable_with => 'Submitting...' %>
    <% end %>

</div>

然后打开 http://localhost:3000/groups/new,可以见到成果

    1. git 存档
    1. 建立 create action,接收数据并储存
      目前还只是个表单画面,无法将数据送出后成功建立出一笔讨论版的数据,缺了 action create。如果此时你按下 Submit,会看到错误。
      所以这时候,我们要实作 create action,接收 new 里的表单送出的信息,变成一笔存在数据库里的数据。

修改 app/controllers/groups_controller.rb

    1. git 存档

4-3 实作讨论群“浏览”功能

    1. 建立 show action 略
    1. 加入 app/views/groups/show.html.erb
<div class="col-md-12">
  <div class="group">
    <%= link_to("Edit", edit_group_path(@group), class: "btn btn-primary pull-right")%>
  </div>
  <h2><%= @group.title %></h2>
  <p><%= @group.description %></p>
</div>
  • git 保存

4-4 实作讨论群“编辑”功能

    1. 建立 edit action 参上,略
    1. 建立 edit action 的表单
# app/views/groups/edit.html.erb
<div class="col-md-4 col-md-offset-4">
    <h2>编辑讨论版</h2>

    <hr>
    <%= form_for @group do |f| %>

    标题
    <%= f.text_field :title %>
    <br>
    叙述
    <br>
    <%= f.text_area :description %>
    <br>

    <%= f.submit "Submit", :disable_with => 'Submiting...' %>
    <% end %>

</div>
    1. git 存档
    1. 实作 update action 略
    1. git

4-5 实作讨论群“删除”功能

    1. 建立 delete action
    1. git 存档

4-6 限制“标题为空”的Group,不能被新增

  • 1: 在 Group model 加入“标题限制”
# app/models/group.rb
class Group < ApplicationRecord
 validates :title, presence: true
end

这样一来,就算送出了空的表单,也不会产生任何纪录。

但我们真正希望达到的效果是像这样子的,送出了空表单,使用者能够确切地知道,自己是因为什么错误被拦下

  • 2: 在 groups_controller 里面加入储存失败的判断
# app/controllers/groups_controller.rb
  def create
    @group = Group.new(group_params)

    if @group.save
      redirect_to groups_path
    else
      render :new
    end
  end

然后修改 app/views/groups/new.html.erb

form_for 下方加入这一段:

<% if @group.errors.any? %>
<ul>
  <% @group.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
</ul>
<% end %>
  • 3 : git 存档

  • 4 : 修改 edit action

# app/controllers/groups_controller.rb
  def update
    @group = Group.find(params[:id])
    if @group.update(group_params)
      redirect_to groups_path, notice: "Update Success"
    else
      render :edit
    end
  end

然后修改 app/views/groups/edit.html.erb
也在 form_for 下方加入这一段:

<% if @group.errors.any? %>
<ul>
  <% @group.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
</ul>
<% end %>
  • 5 : git 存档

4-7 共用“表单”

把 new 与 edit 重复的表单代码,抽成一个共用文件
我们观察到,new 与 edit 都有相同的“表单代码”,显得相当累赘。在这里我们可以利用一个 Rails 内建的架构 partial去整理设计。

  • 1: 产生 app/views/groups/_form.html.erb
<%= form_for @group do |f| %>
<% if @group.errors.any? %>
<ul>
  <% @group.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
</ul>
<% end %>
标题
<%= f.text_field :title %>
<br>
叙述
<br>
<%= f.text_area :description %>
<br>

<%= f.submit "Submit", :disable_with => 'Submiting...' %>
<% end %>
  • 2: 修改 app/views/groups/new.html.erb
# app/views/groups/new.html.erb
<div class="col-md-4 col-md-offset-4">
    <h2>新增讨论版</h2>

    <hr>

    <%= render "form" %>

</div>
  • 3: 修改 app/views/groups/edit.html.erb
# app/views/groups/edit.html.erb
<div class="col-md-4 col-md-offset-4">
    <h2>编辑讨论版</h2>
    <hr>

    <%= render "form" %>
</div>
  • 4: git 存档

4-8 将表单换为 Bootstrap 提供的版型

虽然我们已经有看起来还可以的表单,但是 Bootstrap 本身提供的表单版型更棒。

  • 1: 修改 app/views/groups/_form.html.erb
# app/views/groups/_form.html.erb
<%= form_for @group do |f| %>

<div class="form-group">
    <div class="form-group string optional">
        <%= f.label "title", :class => "string optional control-label" %>
        <%= f.text_field :title, :class => "string optional form-control" %>
    </div>

    <div class="form-group string optional">    # 这段代码很啰嗦
        <%= f.label "description", :class => "string optional control-label" %>
        <%= f.text_area :description, :class => "string optional form-control" %>
    </div>

</div>
<%= f.submit "Submit", class: "btn btn-primary", data: { disable_with: "Submiting..." } %>
<% end %>
  • 2: git 存档
  • 3: 使用 SimpleForm 简化

首先我们要来安装 simple_form
打开 Gemfile,然后新增一行 gem 'simple_form'

# Gemfile
gem 'bootstrap-sass'
+ gem 'simple_form'

bundle install , 安装 gem

  • 4: 安装 simple_form for bootstrap 的设定

终端执行 rails generate simple_form:install --bootstrap
然后重开 rails s
这个指令会产生两个文件
config/initializers/simple_form.rb
config/initializers/simple_form_bootstrap.rb (这个是 Bootstrap 表单的“布景”)

  • 5: 修改 app/views/groups/_form.html.erb
# app/views/groups/_form.html.erb

<%= simple_form_for @group do |f| %>
  <div class="form-group">
    <%= f.input :title, input_html: { class: "form-control"} %>
    <%= f.input :description, input_html: { class: "form-control"} %>
  </div>
  <%= f.submit "Submit", class: "btn btn-primary", data: { disable_with: "Submiting..." } %>
<% end %>

这样,新的界面更加简洁好看

  • 6: git 存档
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容