如何在 Rails 2.3.x 中创建时清理对象?
在我的搜索中,我主要找到了在输出或清理单个输入框时清理数据的方法:
<%=h @name %> OR ['name = ?', params[:name]]
但是,我正在创建一个像这样的对象:
@user = User.new( params[:user] )
现在,我可以一一清理 params[:user] 哈希中的每个键,但是我确信有更优雅的技术。
In my search I mainly found ways to sanitize data when outputting OR sanitizing single input boxes using:
<%=h @name %> OR ['name = ?', params[:name]]
However, I'm creating an object like so:
@user = User.new( params[:user] )
Now, I could sanitize each key in the params[:user] hash one by one, but I'm sure there is a more elegant technique.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果这是出于优化原因,请使用“Sanitize” gem。然而,既然你谈论的是在每个领域都这样做,那么这里就有点不对劲了。 ActiveRecord 已经转义输入以避免 SQL 注入问题,但是您不需要对进入数据库的每一个内容进行 HTML 转义(如果您想以某种方式处理原始数据,这样做可能会导致以后出现问题) )。出于性能原因,在进入数据库之前您可能想要清理的唯一内容是富文本编辑器输入字段之类的内容,例如来自 TinyMCE 的数据,您实际上希望根据白名单过滤数据,而不是只需通过简单的字符串转换来转义它即可。
If this is for optimization reasons, use the 'Sanitize' gem. However, since you talk about doing it for every single field, something smells a little wrong here. ActiveRecord already escapes input to avoid SQL injection problems, but you shouldn't need to HTML-escape every single thing that goes into your database (and doing so could cause issues later down the line if you want to process the original data in some way). The only things you may want to sanitize before they go into the database, for performance reasons, are things like Rich Text Editor input fields, such as data coming from TinyMCE, where you actually want to filter the data against a white-list, not just escape it with simple string conversions.