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”

2014-07-26 20:45 GMT-03:00 Kurt M. [email protected]:

it doesn’t give me the type of validators for each attribute.
@attributes=[:full_prompt], @options={}>],
“full_prompt”=>[{“attributes”=>[“full_prompt”], “options”=>{}}],

https://groups.google.com/d/msgid/rubyonrails-talk/972fd145-9b6b-46ee-90c9-289035a1c6ad%40googlegroups.com?utm_medium=email&utm_source=footer

.
For more options, visit https://groups.google.com/d/optout.


Att,
Antônio Augusto de Sousa Britto
Systems Analyst & Software Developer
+553491382738

https://www.facebook.com/augustobr https://twitter.com/xtrdev
http://br.linkedin.com/in/antoniobr/ https://github.com/antoniosb
https://plus.google.com/u/0/111953897116031502239/