美文网首页
四(上)、rails的控制器的CRUD

四(上)、rails的控制器的CRUD

作者: 求墨者 | 来源:发表于2019-05-29 18:12 被阅读0次

    Step 0. git分支

    $ git checkout -b ch03

    Step 1. 增

    app/controllers/groups_controller.rb

    class GroupsController < ApplicationController
      def new
        @group = Group.new
      end
      
      def create
        @group = Group.new(group_params)
        @group.save
    
        redirect_to groups_path
      end
    
      private
    
      def group_params
        params.require(:group).permit(:title, :description)
      end
    end
    

    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>
    

    Step 2. 查

    app/controllers/groups_controller.rb

    class GroupsController < ApplicationController
      def show
        @group = Group.find(params[:id])
      end
    end
    

    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>
    

    Step 3. 改

    app/controllers/groups_controller.rb

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

    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>
    

    app/controller/groups_controller.rb

    class GroupsController < ApplicationController
       def update
         @group = Group.find(params[:id])
     
         @group.update(group_params)
     
         redirect_to groups_path, notice: "Update Success"
       end
    end
    

    Step 4. 删

    app/controllers/groups_controller.rb

    class GroupsController < ApplicationController
      def update
        @group = Group.find(params[:id])
    
        @group.update(group_params)
    
        redirect_to groups_path, notice: "Update Success"
      end
    end
    

    Step 5. git存档

    $ git add .
    $ git commit -m "implement groups#crud"
    

    相关文章

      网友评论

          本文标题:四(上)、rails的控制器的CRUD

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