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
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.