redirect_to @article和article_path之间有什么区别

时间:2016-03-04 09:18:40

标签: ruby-on-rails

我正在关注此导轨指南。我有以下代码

class ArticlesController < ApplicationController
    def new
    end

    def show
        @article = Article.find(params[:id])
    end
    def create
        @article = Article.new(article_params)
        @article.save

        redirect_to @article
    end


    private 

        def article_params
            params.require(:article).permit(:title, :text)
        end
end

在上面的代码中,在create动作中,我将@article修改为article_path。我认为这与路线相同。

Prefix Verb   URI Pattern                  Controller#Action
welcome_index GET    /welcome/index(.:format)     welcome#index
         root GET    /                            welcome#index
     articles GET    /articles(.:format)          articles#index
              POST   /articles(.:format)          articles#create
  new_article GET    /articles/new(.:format)      articles#new
 edit_article GET    /articles/:id/edit(.:format) articles#edit
      article GET    /articles/:id(.:format)      articles#show
      # the above route
              PATCH  /articles/:id(.:format)      articles#update
              PUT    /articles/:id(.:format)      articles#update
              DELETE /articles/:id(.:format)      articles#destroy

所以根据路线,我提到了article_path。但是当我这样做时,它会将我重定向到/ articles而不是/ articles /:id

任何人都可以解释我发生了什么。

3 个答案:

答案 0 :(得分:1)

article_path需要使用article.id@article的参数调用(响应to_param的对象)

答案 1 :(得分:1)

要获得正确的重定向,您必须使用redirect_to article_path(@article)。这样Rails知道它应该重定向到哪个文章。

答案 2 :(得分:1)

这对我来说非常明显。

当您重定向到@article时,您将重定向到存储在变量中的该实例定义的那篇文章。这肯定意味着/ articles /:id,其中:id是存储在变量中的那篇文章的id。

但是当你重定向到articles_path时,你不会去特定的文章,而是去所有文章的URL,即/ articles。如果你重定向到article_path(现在是单数)而没有告诉你想要哪个文章,你将被重定向到相同的位置,你可以找到所有文章,即/ articles

这只是一个思考REST调用语义的问题。

希望它有所帮助!

相关问题