简体   繁体   English

rails控制器中的params验证

[英]rails params validation in controller

Is there a best practice to validate params in a controller? 是否有最佳实践来验证控制器中的参数?

@user = User.find_by_id(params[:id]) 

If I tamper with the param to give it an invalid :id param, say by visiting "/users/test", I can generate the following error: 如果我篡改param给它一个无效的:id param,比如通过访问“/ users / test”,我可以生成以下错误:

Conversion failed when converting the nvarchar value 'test' to data type int.

I am thinking right now of params that won't go straight to a model and can be validated by model validations. 我现在正在考虑不能直接进入模型的params,并且可以通过模型验证进行验证。

Yes you should always validate your parameters. 是的,您应该始终验证您的参数。 People can always mess around with the parameters in their web browser's address bar, or modify parameters stored in the DOM. 人们总是可以在Web浏览器的地址栏中查看参数,或者修改存储在DOM中的参数。 Another example where parameters can be screwed up is if the webpage is left open a long time. 可以搞砸参数的另一个例子是网页是否长时间打开。 Imagine someone is viewing the page "/users/3/edit" and leaves it open for an hour, then hits refresh. 想象一下有人正在查看页面“/ users / 3 / edit”并将其打开一小时,然后点击刷新。 In the mean time that user may have been deleted. 同时用户可能已被删除。 You don't want your website to crash - it should handle that gracefully. 你不希望你的网站崩溃 - 它应该优雅地处理它。

Depending on your database and adapter, doing User.find_by_id("test") will not crash. 根据您的数据库和适配器,执行User.find_by_id("test")不会崩溃。 But your database/adapter was not able to convert the string in to an integer. 但是您的数据库/适配器无法将字符串转换为整数。 One thing you can do in this particular case is use Ruby's .to_i method. 在这种特殊情况下你可以做的一件事就是使用Ruby的.to_i方法。

User.find_by_id(params[:id].to_i)

If params[:id] = "12" , Ruby will convert that to the integer 12 and the code will run fine. 如果params[:id] = "12" ,Ruby会将其转换为整数12 ,代码运行正常。 If params[:id] = "test" , Ruby will convert that to the integer 0 , and you should never have a database record with an ID of 0. 如果params[:id] = "test" ,Ruby会将其转换为整数0 ,并且您永远不应该拥有ID为0的数据库记录。

You can also use regular expressions to test if a string is an integer . 您还可以使用正则表达式来测试字符串是否为整数

But in general, yes, try to always validate your parameters so you can handle errors gracefully and control the data coming in. 但总的来说,是的,尝试始终验证您的参数,以便您可以优雅地处理错误并控制进来的数据。

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

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