三、rails模型-控制器-视图
2019-05-24 本文已影响0人
求墨者
Step 0. git
分支
$ git checkout -b ch02
Step 1. 设计Group
的model
结构
字段 | 类型 | 描述 |
---|---|---|
title | string | 标题 |
description | text | 详情 |
$ rails g model group title:string description:text
$ rake db:migrate
Step 2. 产生groups
的controller
$ rails g controller groups
app/controllers/groups_controller.rb
class GroupsController < ApplicationController
def index
@groups = Group.all
end
end
Step 3. groups
的controller
内函数对应的视图
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>
Step 4. 资源路由
config/routes.rb
Rails.application.routes.draw do
resources :groups
root 'welcome#index'
end
Step 5. 模拟数据
(可选操作)pry-rails
$ rails c
> Group.create(title: "Board 1", description: "Board 1 body")
> Group.create(title: "Board 2", description: "Board 2 body")
Step 6. git
存档
$ git add .
$ git commit -m "create groups index"