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

前端 未结 7 681
悲&欢浪女
悲&欢浪女 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:46

    I faced another problem using Rails 4.2.4 and PostgreSQL adapter (pg) and custom validator for my json field.

    In the following example:

    class SomeController < BaseController
      def update
        @record.json_field = params[:json_field]
      end
    end
    

    if you pass invalid JSON to

    params[:json_field]
    

    it is quietly ignored and "nil" is stored in

    @record.json_field
    

    If you use custom validator like

    class JsonValidator < ActiveModel::Validator
      def validate(record)
        begin
          JSON.parse(record.json_field)
        rescue
          errors.add(:json_field, 'invalid json')
        end
      end
    end
    

    you wouldn't see invalid string in

    record.json_field
    

    only "nil" value, because rails does type casting before passing your value to validator. In order to overcome this, just use

    record.json_field_before_type_cast
    

    in your validator.

提交回复
热议问题