显然,用户生成的评论内容的html_safe方法确实不是一个好的解决方案。然而,到目前为止,这是我能够实现以下功能的唯一解决方案:我想让用户只需在注释表单中输入其他注释的迭代ID就可以引用另一个注释,如“#14” “(引用该条的评论14)。然后在内容输出中将#14替换为“[quoted_comment.content]”。
这是我在评论模型中的代码:
def content_with_quotes
if content.match(/(#([0-9]+))\s/)
comment_content = content
comment_content.scan(/(#([0-9]+))\s/) do
if quoted_comment = Comment.where(article_id: self.article_id).where(iteration_id: $2).first
if quoted_comment.created_at < self.created_at
return comment_content.sub(/(#[0-9]+)\s/, "<i>'#{quoted_comment.content}'</i> ")
end
end
end
else
return content
end
end
然后在我的评论视图中,我将其应用于comment.content_with_quotes.html_safe,一切正常。
所以,这就是我想要的,并且它有效,但当然这个html_safe方法对于用户提交的内容来说是个坏主意,因为它可能不是html安全的。
有关如何在不执行html_safe方法的情况下处理我的功能的任何建议?
答案 0 :(得分:2)
我会考虑使用白名单方法并使用HTML Sanitizer方法来清理字符串。
请参阅http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html