目标
建立图书管理后台,实现图书CRUD、会员系统、 “上架与下架” 一键切换,借书单。
在本教程中两个符号 “*…” 中间插入的代码新增代码。
1、配置路由
设定后台图书的 CURD、前台图书的路由
config/routes.rb
Rails.application.routes.draw do
root 'welcome#index'
* resources :users
* resources :sessions
resources :books
namespace :admin do #使用命名空间 namespace
resources :books
end
* # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
2、建立 Book 数据表
2.1 数据库中建立 book 数据表
$ rails g migration create_books
db/migrate/xxxx一堆数字xxxx_create_books.rb
class CreateBooks < ActiveRecord::Migration[5.1]
* def change
* create_table :books do |t|
t.string :title
t.text :text
t.timestamps
* end
* end
end
2.2 建立 book 模型
$ touch app/models/book.rb
app/models/book.rb
class Book < ApplicationRecord
end
2.3 测试
终端进入 rails c (后台金手指)
rails c #进入 rails 金手指
u = Book.new
u.title = "Hello"
u.text = "World"
u.save
exit #退出 rails 金手指
3、实现 Book 后台的 CRUD
3.1 Book的New
终端执行
mkdir app/controllers/admin
touch app/controllers/admin/books_controller.rb
配置文件 app/controllers/admin/books_controller.rb
class Admin::BooksController < ApplicationController
# 使用命名空间 namespace ,class的命名使用 Admin::BooksController 格式
def new
@book = Book.new
end
def create
@book = Book.new(book_params)
if @book.save
#查询单个数据必须传递参数实现检索定位,例如@book
redirect_to book_path(@book)
#重定向 >> 图书 show 页面
else
render "new"
end
end
private
#健壮参数,简化参数代码,实现 rails 预筛选安全机制。
def book_params
params.require(:book).permit(:title, :text)
end
end
终端执行
mkdir app/views/admin/books
touch app/views/admin/books/new.html.erb
配置文件 app/views/admin/books/new.html.erb
<h1>新书上架</h1>
#使用命名空间 namespace ,传递参数使用数组[:admin, @book]
<%= form_for [:admin, @book] do |f| %>
<p>
<%= f.label :title %>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit "提交"%>
</p>
<% end %>
3.2 Book的show
修改文件 app/controllers/admin/books_controller.rb
class Admin::BooksController < ApplicationController
def index
@books = Book.all
end
* def new
* end
* def create
* end
def show
@book = Book.find(params[:id])
end
end
终端执行
book 后台新建的图书,要让所有人都看到,需要新建文件 app/views/books
mkdir app/views/books
touch app/views/books/show.html.erb
touch app/views/admin/books/index.html.erb
配置图书展示页 app/views/books/show.html.erb
<h1>图书简介</h1>
<p>
<strong>书名:</strong>
<%= @book.title %>
</p>
<p>
<strong>简介:</strong>
<%= @book.text %>
</p>
3.3 Book的edit
修改文件 app/controllers/admin/books_controller.rb