Rails 4.0.4 w/ Postgres
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已创建初始值设定项string.rb:
require 'json'
class String
def is_json?
begin
!!JSON.parse(self)
rescue
false
end
end
end我没有获得任何成功...我仍然使用MultiJson::ParseError,而不是通过验证。
有什么建议吗?
我的灵感来自于这个stackoverflow thread
发布于 2016-08-09 21:32:26
我来晚了一点,但我认为你的方法是正确的。但是,您不需要修补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发布于 2014-08-01 07:20:56
也许使用store_accessor会有所帮助。
class MyModel < ActiveRecord::Base
store_accessor :my_jason_attribute
validate_presence_of :my_json_attribute
...这是documentation。查看备注:
注意:如果您使用的是特定于PostgreSQL的列,如hstore或json,则不需要由store提供的序列化。只需使用store_accessor来生成访问器方法。请注意,这些列使用字符串键值哈希,不允许使用符号进行访问。
希望这能有所帮助。
https://stackoverflow.com/questions/23138474
复制相似问题