【问题标题】:How to validate a json type attribute如何验证 json 类型属性
【发布时间】:2014-04-17 16:20:21
【问题描述】:

带有 Postgres 的 Rails 4.0.4

Ruby 2.1.1

我正在使用具有 JSON 类型属性的模型。

这里是迁移

def change
    create_table :my_models do |t|
      t.json :my_json_attribute, :null => false

      t.timestamps
    end
end

我想在我的表单中验证此属性,然后在数据库中保存或更新。

今天我收到一个令人讨厌的 JSON 解析器错误 (JSON::ParserError) 而不是我的表单上的友好消息。我故意在我的表单中提供不正确的 JSON 输入以检查验证是否有效以及我是否得到友好要求验证 JSON 字符串的消息......但我什至不确定如何检查是否调用了 attribute_in_json_format

在我的模型类中,我有这样的东西:

class MyModel < ActiveRecord::Base
  validate_presence_of :my_json_attribute

  validate :attribute_in_json_format

protected
  def attribute_in_json_format
    errors[:base] << "not in JSON format" unless my_json_attribute.is_json?
  end
end

创建了一个初始化字符串.rb:

require 'json'

class String
  def is_json?
    begin
      !!JSON.parse(self)
    rescue
      false
    end
  end
end

我没有取得任何成功......我仍然会去 MultiJson::ParseError 而不是通过验证。

有什么建议吗?

我的灵感来自这个stackoverflow thread

【问题讨论】:

  • 如果您收到 json 解析错误,那么您的输入字符串已损坏/无效。您需要查看该字符串并找出问题所在。要么它最初生成错误,要么在传输过程中损坏。但无论是什么原因,摆弄你的红宝石都无济于事,因为这不是问题所在。

标签: json validation ruby-on-rails-4


【解决方案1】:

我有点晚了,但我认为你的方法是正确的方向。但是,您不需要对 String 类进行猴子补丁。你可以这样做:

validate :attribute_in_json_format

private

def attribute_in_json_format
  JSON.parse(my_json_attribute.to_s)
rescue JSON::ParserError
  errors[:base] << "not in JSON format"
end

【讨论】:

    【解决方案2】:

    也许使用store_accessor 会有所帮助。

    class MyModel < ActiveRecord::Base
      store_accessor :my_jason_attribute
      validate_presence_of :my_json_attribute
    ...
    

    这里是documentation。检查注释:

    注意 - 如果您使用 PostgreSQL 特定的列,例如 hstore 或 json 不需要 store 提供的序列化。简单地 使用 store_accessor 来生成访问器方法。意识到 这些列使用字符串键控哈希并且不允许访问 使用符号。

    希望这会有所帮助。

    【讨论】:

    • 这看起来很有希望。我会尽快尝试的。
    • 另一个相关的非常重要的注意注意:除了唯一性之外的默认验证将起作用。例如,如果您想使用 hstore 检查唯一性,则需要使用自定义验证来处理它。
    猜你喜欢
    • 2014-01-28
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多