我是 Rails 的初学者。我现在正在通过“Beginning Rails 4”一书学习 Rails。我想问你关于传递给 params 方法的“参数”。以下是典型的 rails Controller 之一。
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
是的,这只是一个典型的评论 Controller ,用于创建附加到文章的评论。 Comment 模型“属于”文章模型,而文章模型“有很多”评论。
看看destroy方法。
def destroy
@comment = @article.comments.find(params[:id])
-- snip --
end
它通过 find(params[:id]) 找到与文章相关的评论。我的问题是,params[:id] 到底来自哪里?
它来自URL吗?或者,每当创建任何评论记录时,rails 是否会自动保存 params 哈希?所以我们可以通过 find(params[:id]) 找到任何评论?
load_article 方法类似。
def load_article
@article = Article.find(params[:article_id])
end
它通过 params[:article_id] 查找文章。这个 params[:article_id] 来自哪里? rails是怎么通过这个找到文章的?
最佳答案
params[:id]
是用于唯一标识 Rails 应用程序中(RESTful)资源的字符串。它位于资源名称后面的 URL 中。
例如,对于名为 my_model
的资源, GET
请求应对应于类似 myserver.com/my_model/12345
的 URL , 其中 12345
是 params[:id]
标识 my_model
的特定实例.其他 HTTP 请求(PUT、DELETE 等)及其对应的 RESTful 请求类似。
您应该阅读 Rails routing如果您仍然对这些概念和术语感到困惑,请查看它对 RESTful 架构的解释。
关于ruby-on-rails - 参数在哪里[:id] come from in rails?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33651377/