Rails: Search, Initialize, or Create RESTful

I have an application in which there are cities. I am looking for some suggestions on how to RESTfully structure a controller so that I can search, initialize and create city records using AJAX queries. For instance:

  • For text box city_name
  • The user enters the name of the city, for example, "Paris, France."
  • The application checks this location to find out if such a city is already in the database
  • If there is, it returns a city object
  • If this does not happen, he returns a new record, initialized with the name “Paris” and the country “France”, and prompts the user to confirm that they want to add this city to the database.
  • If the user says yes, the record is saved. If the record is not discarded and the form is cleared.

Now my first approach was to change the Create action to use find_or_create, so an AJAX message before cities_pathwill return the existing city or create and return it.

This is normal ... However, it would be better to configure the controller actions that will accept string input, search or initialization and return, and then create only if the user confirms that the generated record is correct. An ideal script would put it all in one action, so an AJAX request can go to that URL, the server responds with JSON objects, and javascript can handle things from there. I would like to save all the client part of the user interaction logic and minimize the number of requests required to achieve this goal.

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

+3
source share
1 answer

One option is to use an existing one? Method:

if City.exists?(:name=>params[:city])
  @city = City.find_by_name(params[:city])
else
  @city = City.new(:name=>params[:city])
end

Comment based update:

#show = /city/:id, :id can be int or string

def show
  if params[:id].to_i > 0
    @city = City.find(params[:id])
  elsif City.exists?(:name=>params[:id])
    @city = City.find_by_name(params[:id])
  else
    return redirect_to(:action=>:new, :name=>params[:id])
  end
end

def new
  @city = City.new(params[:name])
end
0
source

All Articles