简体   繁体   English

Ruby on Rails-参数上的禁止属性?

[英]Ruby on Rails - Forbidden Attributes on params?

Im trying to redirect someone after they click a button and I keep getting the following error: 我试图在某人单击按钮后重定向,但我不断收到以下错误:

ActiveModel::ForbiddenAttributesError ::加载ActiveModel ForbiddenAttributesError

Extracted source (around line #20): 提取的源(第20行附近):

It is throwing the error on the @post = Post.new line. 它在@post = Post.new行上引发错误。

def create   
@post = Post.new(params[:post])

if @post.save
 redirect_to posts_path, :notice => "Your post was saved"

I am very new to Ruby and at the moment I am very confused of what this means. 我对Ruby很陌生,此刻我对这意味着什么感到非常困惑。 I am just following a tutorial and mine isnt working. 我只是在跟随一个教程,而我的却没有工作。 If anyone could help that would be awesome :D 如果有人可以帮助,那将是很棒的:D

@post = Post.new(params[:post]) 

... is no longer used in the latest versions of rails. ...在最新版本的rails中不再使用。 The problem is that it provided weak security. 问题在于它提供的安全性较弱。 Someone who was updating their user profile (for example) could theoretically insert an attribute like "administrator: true" to change themselves into an administrator (if that's how admin flag is stored) 理论上,正在更新用户配置文件的用户可以插入“ administrator:true”之类的属性以将自己更改为管理员(如果这是存储admin标志的方式)

Strong parameters now require that you explicity specify which attributes you want to allow to be entered. 强大的参数现在要求您明确指定要允许输入的属性。

So nowadays we do... 所以现在我们要做...

@post = Post.new(post_params)

And we have a method later in the controller that specifies the permitted attributes, and looks like... 我们稍后在控制器中有一个方法,用于指定允许的属性,如下所示:

def post_params
  params.require(:post).permit(:title, :body)
end

While I don't have quite enough of your code to specifically answer the question, I can probably get pretty close (minus some column/attribute naming). 尽管我的代码不足以专门回答这个问题,但我可能会很接近(减去一些列/属性命名)。 With strong_params now the standard for Rails applications, you'd probably be looking to do something more like: 现在,strong_params是Rails应用程序的标准,您可能希望做更多的事情:

def create   
  @post = Post.new(post_params)

  if @post.save
    redirect_to posts_path, :notice => "Your post was saved"
  else
    #other stuff here
  end
end

private
def post_params
  params.require(:post).permit(:content, ....etc) #I took a guess at the attributes you are passing through your params on the create.
end

For a little extra easy-reading on the history/reason: http://blog.8thlight.com/will-warner/2014/04/05/strong-parameters-in-rails.html 有关历史/原因的更多易读内容,请访问: http : //blog.8thlight.com/will-warner/2014/04/05/strong-parameters-in-rails.html

Let me know if you'd like any additional clarification. 让我知道您是否还需要其他说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM