簡體   English   中英

如何驗證json類型屬性

[英]How to validate a json type attribute

帶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線程中汲取了靈感

也許使用store_accessor會有所幫助。

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

這是文檔 檢查注意:

注意-如果使用的是PostgreSQL特定的列(例如hstore或json),則不需要store提供的序列化。 只需使用store_accessor即可生成訪問器方法。 請注意,這些列使用字符串鍵哈希,並且不允許使用符號進行訪問。

希望這可以幫助。

我有點晚了,但我認為您的方法是朝正確的方向前進。 但是,您不需要猴子修補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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM