《Ruby on Rails 教程》第 5 章

282 阅读1分钟

完善布局

编辑 app/views/layouts/application.html.erbapp/views/static_pages/home.html.erb

布局代码

添加 Bootstrap

添加 gem

gem 'bootstrap-sass', '3.4.1'

新建 CSS 文件

touch app/assets/stylesheets/custom.scss

编辑 app/assets/stylesheets/custom.scss

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

CSS 代码

重启项目

局部视图

代码详情

Sass

Sass 代码

Rails 路由

具名路由,编辑 config/routes.rb

Rails.application.routes.draw do
    root 'static_pages#home'
    get '/help', to: 'static_pages#help'
    get '/about', to: 'static_pages#about'
    get '/contact', to: 'static_pages#contact'
end

同时需要修改测试代码,让测试通过

布局中链接的测试

生成测试模板,使用集成测试

bin/rails generate integration_test site_layout

编写测试代码

添加 gem

gem 'rails-controller-testing'
bundle
bin/rails test:integration # 只执行集成测试
bin/rails test # 执行整个测试

用户注册

生成 Users 控制器(包含new 动作)

bin/rails generate controller Users new

config/routes.rb

Rails.application.routes.draw do
  get 'users/new'
  root 'static_pages#home'
  get '/help', to: 'static_pages#help'
  get '/about', to: 'static_pages#about'
  get '/contact', to: 'static_pages#contact'
  get '/signup', to: 'users#new'
end

test/controllers/users_controller_test.rb

require "test_helper"

class UsersControllerTest < ActionDispatch::IntegrationTest
  test "should get new" do
    get signup_path
    assert_response :success
  end
end

app/views/static_pages/home.html.erb

<div class="center jumbotron">
    <h1>Welcome to the Sample App</h1>
    <h2>
    This is the home page for the
    <a href="https://www.railstutorial.org/">Ruby on Rails Tutorial</a>
    sample application.
    </h2>
    <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %>
</div>

app/views/users/new.html.erb

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<p>This will be a signup page for new users.</p>

执行测试,并打开页面,都能成功!