In continuing with my side project relating to maps and restaurants, I wanted to get things a little more interactive. The next step is to combine all my restaurants I have the in database, and put them on the map. To do this though, I needed to get the Restaurant Model objects into javascript so I could dynamically add them to as markers on the map.
The first step was to define a new controller action in my “app/controllers/restaurants_controller.rb” file. For now, this will just find the first item in the DB and render it as a JSON object. In the long run, this will return a list of recommended restaurants:
def recommendations @restaurant = Restaurant.find(:first) render :json => @restaurant end
Next, I needed to make that controller accessible via a URL. My initial idea is to open up the URL like “/restaurants/recommendations” to return the list. I modified the “config/routes.rb” file, and restarted the server:
match "/restaurants/recommendations" => "restaurants#recommendations"
If I point the browser to this URL, I see the JSON I was expecting to see. In this case, it is returning the restaurant “Watts Grocery”:
{ "name":"Watts Grocery", "city":null, "created_at":"2012-03-12T02:08:29Z", "description":null, "id":4, "lattitude":"36.0164193", "longitude":"-78.9189592", "openmap_id":266302295, "state":null, "updated_at":"2012-03-12T02:08:29Z" }
Next up, I’ll show how to make a call in javascript to get this JSON string and parse it into an object so it can be displayed on the map.