【发布时间】: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