params [:id]来自rails?

Soo*_*e J 0 ruby-on-rails params

我是Rails的初学者.我现在正在学习使用"Beginning Rails 4"这本书.我想问你关于传递给params方法的'参数'.以下是典型的轨道控制器之一.

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 
Run Code Online (Sandbox Code Playgroud)

是的,这只是一个典型的评论控制器,用于创建附加到文章的评论.评论模型"属于"文章模型,文章模型"有很多"评论.

看看destroy方法.

def destroy
  @comment = @article.comments.find(params[:id])
  -- snip --
end
Run Code Online (Sandbox Code Playgroud)

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

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

load_article方法类似.

def load_article
  @article = Article.find(params[:article_id])
end
Run Code Online (Sandbox Code Playgroud)

它通过params [:article_id]找到一篇文章.这个参数[:article_id]来自哪里?rails如何找到这篇文章?

Leo*_*ito 5

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

例如,对于一种称为资源my_model,一个GET请求应当对应于一个URL等myserver.com/my_model/12345,其中,12345params[:id]用于识别的该特定实例my_model.其他HTTP请求(PUT,DELETE等)及其RESTful对应项的类比如下.

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