如何在Ruby on Rails中使用new,index,show和create? [关闭]

问题描述 投票:-1回答:2

我是rails的新手,无法弄清楚这些(new,index,show和create)方法是如何工作的。例如

class NameofController<ApplicationController
   def new
   end

   def show
   end
   .
   .
end
ruby-on-rails-5
2个回答
1
投票

我将向您展示这对于一个简单的博客文章应用程序是如何工作的,因为这是我在开始使用Rails时学习它的最佳方式。简而言之,以下是您通常使用以下CRUD(创建,读取,更新和销毁)功能的方式:


show:使用此选项显示已创建的单个帖子。

new:使用它来告诉你的程序如何创建一个新帖子(我只是在底部的代码中向你展示如何做到这一点)。

create:使用它来告诉你的程序在你实际创建帖子后要做什么(new只是初始化过程,而create实际上用它做了一些事情)。

index:用于显示已创建的所有帖子。这就像所有帖子的主页。


下面是一个基本CRUD的示例(您没有询问更新和销毁方法,但我会将它们包含在代码中,仅供您查看它们如何一起工作)。

    class PostsController < ApplicationController
        def new
            @post = Post.new
          end

          def index
            @posts = Post.search(params[:search])
          end

          def create
            @listing = Listing.new(listing_params)
            @listing.user = current_user
           if @listing.save
             flash[:success] = "Your listing was successfully saved."
             redirect_to listing_path(@listing)
           else
             render 'new'
           end
          end

          def show
            # Note sometimes you don't need to add anything other than declaring the method
          end

          def edit
 # Note sometimes you don't need to add anything other than declaring the method
          end

          def update
            if @post.update(post_params)
              flash[:success] = "Your listing was successfully updated."
              redirect_to listing_path(@listing)
            else
              render 'edit'
            end
          end

          def destroy
            @post.destroy
            flash[:danger] = "Post was successfully deleted"
            redirect_to posts_path
          end

          private
           def post_params
             params.require(:post).permit(:title,:description)
           end
        end

我希望这对你有所帮助。


1
投票

这些似乎是七种常见的资源行动中的四种。

资源路由允许您快速声明给定资源控制器的所有公共路由。您没有为索引,显示,新建,编辑,创建,更新和销毁操作声明单独的路由,而是一条资源丰富的路由在一行代码中声明它们。

浏览器通过使用特定HTTP方法(例如GET,POST,PATCH,PUT和DELETE)请求URL来请求来自Rails的页面。每种方法都是对资源执行操作的请求。资源路由将许多相关请求映射到单个控制器中的操作。

当您的Rails应用程序收到传入的请求时:

DELETE /photos/17

它要求路由器将其映射到控制器操作。如果第一个匹配的路线是:

resources :photos

Rails会将这个请求发送到照片控制器上的销毁操作,并在参数中使用{id:'17'}。

在Rails中,资源丰富的路由提供HTTP谓词和URL与控制器操作之间的映射。按照惯例,每个操作还映射到数据库中的特定CRUD操作。路由文件中的单个条目,例如:

resources :photos

Rails Routing from the Outside In

© www.soinside.com 2019 - 2024. All rights reserved.