![](/img/trans.png)
[英]ActiveModel::ForbiddenAttributesError Ruby On Rails
[英]ActiveModel::ForbiddenAttributesError with Rails 4
我在遵循Rails教程时遇到了错误。 经过一番研究,将@post = Post.new(params[:post])
更改为@post = Post.new(post_params)
解决了我的问题,尽管我仍然不太了解原因。 有什么不同? 为什么我可以在show
使用params[:id]
?
我的posts_controller.rb:
class PostsController < ApplicationController
def new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
答案很简单,当您尝试创建或编辑记录时,将应用强参数系统。 因此,即使没有允许的参数,在show动作中进行简单的SELECT / find也可以正常工作。 但是,必须为每个INSERT或UPDATE动作显式允许控制器中的参数。 这就是使用params.require(:post).permit(:title, :text)
。 您已经说过,如果:post存在,则标题和文本参数是允许的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.