Ruby on rails 将ActiveRecord属性标记为html\u安全
我们有一个带有html属性的ActiveRecord模型(比如说Ruby on rails 将ActiveRecord属性标记为html\u安全,ruby-on-rails,activerecord,html-safe,Ruby On Rails,Activerecord,Html Safe,我们有一个带有html属性的ActiveRecord模型(比如说Post#body)。在post上调用body会返回html\u-safe吗?字符串?例如: class Post < ActiveRecord::Base # is_html_escaped :body or somesuch magic end Post.first.body.html_safe? # => true class Post真的 否则的问题是,我们必须调用raw显示该字段的所有内容。我找到了一
Post#body
)。在post
上调用body
会返回html\u-safe吗?
字符串?例如:
class Post < ActiveRecord::Base
# is_html_escaped :body or somesuch magic
end
Post.first.body.html_safe? # => true
class Post真的
否则的问题是,我们必须调用raw
显示该字段的所有内容。我找到了一种方法:
class Post < ActiveRecord::Base
def message
super.html_safe
end
def message=(new_mess)
new_mess = ERB::Util.html_escape(new_mess.sanitize) unless new_mess.html_safe?
super(new_mess)
end
end
class Post
供参考。我为此制作了一个模块
module SanitizeOnly
def self.included(mod)
mod.extend(ClassMethods)
end
module ClassMethods
def sanitize_on_input_only(*attribute_names)
attribute_names.map(&:to_s).each do | attribute_name |
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{attribute_name}
super.html_safe
end
def #{attribute_name}=(new_val)
new_val = ERB::Util.html_escape(new_val.sanitize) unless new_val.html_safe?
super(new_val)
end
RUBY
end
end
end
end
sanitize_on_input_only :message, :another_attribute, ...