A model's validators as json

Hey guys,

I’ve been working with Rails and a number of frontend js frameworks and libs, including Ember, Angular, and React. While all three libraries are powerful in their own regard, one pain point (for me at least) has always been form validation. I’ve always hated having to keep my model validations (in Rails) in sync with my form validations (in Ember/Angular/React).

Lately, I’ve been attempting to serialize a model’s validators into json. However, while calling as_json on a record will give me back a json hash, it doesn’t give me the type of validators for each attribute.

For example, let’s say I have a model called Assignment. When I create a new Assignment record and call _validators on it, this is what I get.

pry(main)> Assignment.new._validators
=>
{
:title=>[#<ActiveRecord::Validations::PresenceValidator:0x0000010e123900 @attributes=[:title], @options={}>],
:full_prompt=>[#<ActiveRecord::Validations::PresenceValidator:0x0000010e122e60 @attributes=[:full_prompt], @options={}>],
:submission_window=>[#<ActiveRecord::Validations::PresenceValidator:0x0000010e1223c0 @attributes=[:submission_window], @options={}>]
}

``

Now here’s what I get when I add on the as_json call:

pry(main)> Assignment.new._validators.as_json
=>
{
“title”=>[{“attributes”=>[“title”], “options”=>{}}],
“full_prompt”=>[{“attributes”=>[“full_prompt”], “options”=>{}}],
“submission_window”=>[{“attributes”=>[“submission_window”], “options”=>{}}]
}

``

As you can see, calling as_json removes what types of validators were attached to each model attribute.

Has anybody run into a similar situation and/or has a workaround? Thanks for any help.

Kurt

I could guess that the method as_json doesn’t intend to serialize your module/class name. One option is to provide inside each class an attirbute with the name of the validator, i.e. “validation = self.name