Ruby-on-rails 处理用户发送的“字符串包含空字节”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29320369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:09:52  来源:igfitidea点击:

Coping with "string contains null byte" sent from users

ruby-on-railsrubypostgresql

提问by John Smith

I have an API controller that receives information about a media file's path and id3 tags, and saves them to an Active Record instance, using PostgreSQL/Rails.

我有一个 API 控制器,它接收有关媒体文件路径和 id3 标签的信息,并使用 PostgreSQL/Rails 将它们保存到 Active Record 实例。

Sometimes however the user sends strings such as:

然而,有时用户会发送字符串,例如:

"genre"=>"Hip-Hop\u0000Hip-Hop/Rap"

and Rails/Postgres aren't exactly happy about that when trying to persist on save:

当尝试坚持时,Rails/Postgres 对此并不完全满意save

An ArgumentError occurred in internals#receive:

 string contains null byte
 activerecord (3.2.21) lib/active_record/connection_adapters/postgresql_adapter.rb:1172:in `send_query_prepared'

How can I clean this string in Ruby to completely remove null bytes?

如何在 Ruby 中清理此字符串以完全删除空字节?

采纳答案by tpbowden

The gsubmethod on Stringis probably suitable. You can just do string.gsub("\u0000", '')to get rid of them.

上的gsub方法String大概是合适的。你可以做string.gsub("\u0000", '')来摆脱它们。

http://ruby-doc.org/core-2.1.1/String.html#method-i-gsub

http://ruby-doc.org/core-2.1.1/String.html#method-i-gsub