How to validate if a string is json in a Rails model

前端 未结 7 669
悲&欢浪女
悲&欢浪女 2021-01-31 16:03

I\'m building a simple app and want to be able to store json strings in a db. I have a table Interface with a column json, and I want my rails model to validate the value of the

7条回答
  •  借酒劲吻你
    2021-01-31 16:44

    If you don't fancy enterprise-style validators or monkey-patching the String class here's a simple solution:

    class Model < ApplicationRecord
      validate :json_field_format
    
      def parsed_json_field
        JSON.parse(json_field)
      end
    
      private
    
      def json_field_format
        return if json_field.blank?
        begin
          parsed_json_field
        rescue JSON::ParserError => e
          errors[:json_field] << "is not valid JSON" 
        end
      end
    end
    

提交回复
热议问题