我试图在Rails中转义用户生成的内容.我使用raw with sanitize和raw helpers来过滤这样的内容:
raw(sanitize(code,:tags => ['<','h2','h3','p','br','ul','ol','li','code','pre','a'] ))
问题是当我尝试用这样的SQL查询测试它时:
MysqL -u sat -p -h localhost database < data.sql
解决方法
我不相信这可以使用Rails中的默认清理方法.
而是尝试使用Sanitize gem(https://github.com/rgrove/sanitize)
require 'sanitize' allowed_elements = ['h2','a'] code = "<pre>MysqL -u sat -p -h localhost database < data.sql</pre>" Sanitize.fragment(code,elements: allowed_elements) # => <pre>MysqL -u sat -p -h localhost database < data.sql</pre>
要使用此功能将已清理的内容保存到数据库,请在模型中添加一个before_save过滤器,该模型对用户生成的内容进行清理并存储结果,例如:
class MyModel < ActiveRecord::Base ALLOWED_ELEMENTS = ['h2','a'] before_save :sanitize_code private def sanitize_code self.code = Sanitize.fragment(code,elements: ALLOWED_ELEMENTS) end end
<%= raw @instance.code %>