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如何找到这篇文章?
| 归档时间: |
|
| 查看次数: |
3541 次 |
| 最近记录: |