Rails: RESTful Find, Initialize, or Create

Posted by Andrew on Stack Overflow See other posts from Stack Overflow or by Andrew
Published on 2012-04-15T23:24:26Z Indexed on 2012/04/15 23:29 UTC
Read the original article Hit count: 193

Filed under:
|
|

I have an app that has Cities in it. I'm looking for some suggestions on how to RESTfully structure a controller so that I can lookup, initialize, and create city records via AJAX requests. For instance:

  • Given a text field city_name
  • A user enters the name of a City, like "Paris, France"
  • The app checks this location to see if there is such a city in the database already
  • If there is, it returns the city object
  • If there is not, it returns a new record initialized with the name "Paris" and the country "France", and prompts the user to confirm they want to add this city to the database
  • If the user says "Yes" the record is saved. If not the record is discarded and the form is cleared.

Now, my first approach was to change the Create action to use find_or_create, so that an AJAX post to cities_path would result in either returning the existing city or creating it and returning it.

That works ok... However, it would be better to setup controller actions that would take a string input, find , or else initialize and return, then only create if the user confirms the generated record is correct. The ideal scenario would put this all in one action so AJAX request can go to that url, the server responds with JSON objects, and javascript can handle things from there. I'd like to keep all the user-interaction logic client side, and also minimize the number of requests it takes to achieve this.

Any suggestions on the cleanest, most RESTful way to accomplish this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about AJAX