简体   繁体   English

如何验证json类型属性

[英]How to validate a json type attribute

Rails 4.0.4 w/ Postgres 带Postgres的Rails 4.0.4

Ruby 2.1.1 Ruby 2.1.1

I am using a model with a JSON type attribute. 我正在使用带有JSON类型属性的模型。

here the migration 这里迁移

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

      t.timestamps
    end
end

I want to validate this attribute in my form before saved or updated in the database. 我想先在表单中验证此属性,然后再在数据库中保存或更新该属性。

Today I am getting a nasty JSON parser error (JSON::ParserError) instead of a friendly message on my form .. I am purposely giving an incorrect JSON input in my form to check if validation works and if I get a friendly message asking to verify the JSON string ... but I am not even sure how to check whether attribute_in_json_format was called 今天,我收到一个令人讨厌的JSON解析器错误(JSON :: ParserError)而不是表单上的友好消息。.我故意在表单中提供了不正确的JSON输入,以检查验证是否有效以及是否收到友好的消息询问验证JSON字符串...但是我什至不确定如何检查是否调用了attribute_in_json_format

In my model class, I have something like this: 在我的模型课中,我有这样的事情:

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

Created an initializer string.rb: 创建了一个初始化字符串.rb:

require 'json'

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

I am not getting any success ... I am still going to the MultiJson::ParseError instead of going through the validate. 我没有获得任何成功……我仍然要去MultiJson :: ParseError而不是通过验证。

Any suggestion? 有什么建议吗?

I took my inspiration from this stackoverflow thread 我从这个stackoverflow线程中汲取了灵感

Maybe using store_accessor would help. 也许使用store_accessor会有所帮助。

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

Here is the documentation . 这是文档 Check the NOTE: 检查注意:

NOTE - If you are using PostgreSQL specific columns like hstore or json there is no need for the serialization provided by store. 注意-如果使用的是PostgreSQL特定的列(例如hstore或json),则不需要store提供的序列化。 Simply use store_accessor instead to generate the accessor methods. 只需使用store_accessor即可生成访问器方法。 Be aware that these columns use a string keyed hash and do not allow access using a symbol. 请注意,这些列使用字符串键哈希,并且不允许使用符号进行访问。

Hope this helps. 希望这可以帮助。

I am a bit late, but I think that your approach is in the right direction. 我有点晚了,但我认为您的方法是朝正确的方向前进。 However, you don't need to monkey-patch the String class. 但是,您不需要猴子修补String类。 You can do this: 你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM