【发布时间】: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