We should absolutely be using partials in order to make the best use of Ajax in our Rails applications. It will significantly reduce the required amount of client side scripting and make your code more robust.

The jQuery / javascript below shows how one can perform an asynchronous GET request, execute some Ruby code, then render a JSON object... This can quickly become arduous if your client wants lots of "things" loaded in asynchronously.

What not to do (usually)

  // GET request hits controller
  $.get("/ot_restaurants/" + id, params, function(data){

    // Javascript parses JSON object to add new content dynamically
    var description_el = $('#product_description')
    var name_el = $('#product_name');
    var images_el = $('#product_images');

    var s = document.createElement('img');
    s.src = data["image"];
    images_el.appendChild(s);

    description_el.html(data["description"]);
    name_el.html(data["name"]);
    }, "json");

  $('#detailModal').reveal();

& in restaurants_controller.rb

# Restaurants#ot_restaurants renders a JSON object
restaurant = { name: restaurant.restaurant_name, description: restaurant.restaurant_description, image: random_image }
render :json => restaurant

What I recommend

Rather than creating HTML elements using Javascript, just use a partial! It's easy for any developer to get at the content, and your designers won't have to wonder "where does this HTML live in the codebase?" Here's a quick example:

  $.get("/ean_hotels/"+ id, params, function(data){
    $('#hotelModalContent').html(data);
  }, "html");

  $('#hotelModal').reveal();

And the "render" at the end of my controller action in hotels_controller.rb:

render partial: 'hotel_modal_content', locals: { hotel: @hotel, hotel_review_widget: hotel_review_widget }, layout: false 
Tags:

Tad Hosford is a recent addition to the isotope|eleven development team. He graduated from the UAB Electrical and Computer Engineering department in 2009. He says software development is a perfect fit for him because it offers endless opportunities to create and to find new solutions to interesting problems.