Thomas C Thomas C - 3 months ago 31
Ajax Question

Field Validation with API/client setup in Ruby on Rails

I have an issue with validations. I've written a rails app (API only using ActiveRecord and Doorkeeper for protection) which validates every request just fine, it returns the errors in json if a validation error occurs.

now i'm building the client app (also a rails app, which has no db or activerecord) that uses the api. I am able to return the validation errors after a form has been submitted, however we want to implement javascript validation on the client-side before the form is submitted. including a check for uniqueness on some fields.

i'm probably making this harder than it should be but...
how do implement this? Do I use ActiveModel (for simple validation checks)? how would i do a check for uniqueness (i'm only able to access the API through doorkeeper)?
Should i write an ajax request for every field that needs unique validation to the client app which would make a api request to validate the uniqueness of the field?

what is the best solution in your opinion?

Answer

Assuming that you mean you have two Rails apps, one hosting the API (connected to a database) and another hosting the front-end (with no database), my first suggestion would be to cut out one layer of complexity and have your API server also host your frontend. Unless you're architecting this to be a massive system, the extra complexity is unlikely to be worth the scalability benefits.

Anyway, assuming you stick with your current plan, all form data flows through three places of interest:

    [ front-end js ] ---> [ front-end Rails ] ---> [ back-end Rails ]

Each of those places can have its own validation. However, since your back-end Rails and front-end Rails will presumably be enforcing the exact same set of errors, it's mostly redundant to add any validation in your front-end Rails stack. I'd suggest focusing on the edges: have all your validations in the front-end js, and enforce them again in the back-end Rails stack. Your back-end validation errors should flow through the front-end to display properly to the user, in the hopefully-rare case that they're triggered.

For uniqueness checks, I'd recommend -- like you suggested -- that your API expose an endpoint to check the uniqueness of the fields you're concerned about. Or, depending on how likely a collision is, rely on the back-end validations to handle non-unique errors.

Comments