美文网首页
三、rails模型-控制器-视图

三、rails模型-控制器-视图

作者: 求墨者 | 来源:发表于2019-05-24 21:14 被阅读0次

    Step 0. git分支

    $ git checkout -b ch02

    Step 1. 设计Groupmodel结构

    字段 类型 描述
    title string 标题
    description text 详情
    $ rails g model group title:string description:text
    $ rake db:migrate
    

    Step 2. 产生groupscontroller

    $ rails g controller groups

    app/controllers/groups_controller.rb

    class GroupsController < ApplicationController
      def index
        @groups = Group.all
      end
    end
    

    Step 3. groupscontroller内函数对应的视图

    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"
    

    相关文章

      网友评论

          本文标题:三、rails模型-控制器-视图

          本文链接:https://www.haomeiwen.com/subject/dzgbaqtx.html