Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将ActiveRecord属性标记为html\u安全_Ruby On Rails_Activerecord_Html Safe - Fatal编程技术网

Ruby on rails 将ActiveRecord属性标记为html\u安全

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显示该字段的所有内容。我找到了一

我们有一个带有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
显示该字段的所有内容。

我找到了一种方法:

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, ...