带有 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
最佳答案
我有点晚了,但我认为你的方法是正确的。但是,您不需要对 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
关于json - 如何验证 json 类型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23138474/