【问题标题】:Where does params[:id] come from in rails?params[:id] 从哪里来?
【发布时间】:2015-11-11 13:18:32
【问题描述】:

我是 Rails 的初学者。我现在正在通过《Beginning Rails 4》这本书学习 Rails。我想问你关于传递给 params 方法的“参数”。以下是典型的 Rails 控制器之一。

class CommentsController < ApplicationController
  before_action :load_article
  def create
    @comment = @article.comments.new(comment_params)
    if @comment.save
      redirect_to @article, notice: 'Thanks for your comment'
    else
      redirect_to @article, alert: 'Unable to add comment'
    end
  end

  def destroy
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to @article, notice: 'Comment Deleted'
  end

  private
    def load_article
      @article = Article.find(params[:article_id])
    end

    def comment_params
      params.require(:comment).permit(:name, :email, :body)
    end
  end 

是的,这只是一个典型的评论控制器,用于创建附加到文章的评论。 Comment 模型“属于”Article 模型,Article 模型“有很多”cmets。

看看destroy方法。

def destroy
  @comment = @article.comments.find(params[:id])
  -- snip --
end

它通过 find(params[:id]) 找到与文章关联的评论。我的问题是,params[:id] 到底是从哪里来的?

它来自 URL 吗?或者,无论何时创建任何评论记录,rails 都会自动保存参数哈希?所以我们可以通过 find(params[:id]) 找到任何评论?

load_article 方法类似。

def load_article
  @article = Article.find(params[:article_id])
end

它通过 params[:article_id] 找到一篇文章。这个 params[:article_id] 来自哪里? rails 是如何通过 this 找到文章的?

【问题讨论】:

  • 它来自于URL,也许阅读guide的路由部分会帮助你理解它

标签: ruby-on-rails params


【解决方案1】:

params[:id] 是唯一标识 Rails 应用程序中(RESTful)资源的字符串。它位于资源名称之后的 URL 中。

例如,对于名为 my_model 的资源,GET 请求应对应于类似 myserver.com/my_model/12345 的 URL,其中 12345 是标识 my_model 的特定实例的 params[:id]。其他 HTTP 请求(PUT、DELETE 等)及其 RESTful 对应项的类比如下。

如果您仍然对这些概念和术语感到困惑,您应该阅读Rails routing 及其对 RESTful 架构的解释。

【讨论】:

    【解决方案2】:

    params[:id] 确实来自 URL。当您在路由文件中使用resources 时,Rails 会自动为您生成标准的 REST 路由。在您的destroy 示例中,这通常是使用DELETE HTTP 方法对/comments/:id 的请求,其中:id 被添加到params 哈希中,即params[:id]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 2016-09-03
      • 2013-10-20
      • 2011-08-02
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2012-10-20
      相关资源
      最近更新 更多