Ruby on Rails 中的 new、index、show 和 create 如何工作?

Pus*_*mar 3 ruby-on-rails-5

我是 Rails 新手,无法弄清楚这些(新的、索引的、显示的和创建的)方法是如何工作的。例如。

class NameofController<ApplicationController
   def new
   end

   def show
   end
   .
   .
end
Run Code Online (Sandbox Code Playgroud)

Jac*_*ody 5

我将向您展示这对于一个简单的博客文章应用程序是如何工作的,因为这是我开始 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
Run Code Online (Sandbox Code Playgroud)

我希望这对您有帮助。