[英]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.