Test Test
Test Test

Reputation: 53

Rails 3 and Ajax

I need to update my index.html.erb file (for products), but without reloading the whole page. For example I have a column named "Sold", which takes a value "YES" or "NO". And I have a background rake task that updated those values, but I want my index file to be updated to, show the user sees which products are sold or not. I have no idea how to invoke such a change from the rake task. Any help please? Most of the ajax and rails 3 "tutorials" I saw mostly deal with user to server interaction, not the server to user.

Upvotes: 1

Views: 123

Answers (2)

Kibet Yegon
Kibet Yegon

Reputation: 2823

You'd probably add javascript code on your products index page to ping your server to get the products' statuses periodically (every n seconds). This might be an expensive call if you've got many products on your page. So I'd have something like this on your index.html.erb

<script type="text/javascript">
  $('document').ready(function() {
    $.ajax({
      method: 'get',
      url : 'products/ping',
      dataType : 'json',
      success: function (json) {
        // iterate through json objects and update their respective sold status
        // on page.
      }
    });
</script>

Then add the ping route to your products controller which basically responds with a JSON object containing the statuses and id of the products you want to update on your view. So when the Ajax request completes and you get the JSON object, iterate through the products and update the status for that product based on its id. So your action on your products controller would look something like this:

# app/controllers/products_controller.rb
def ping
  respond_to do |format|
    products_sold_statuses = {}
    format.json do
      Products.all.each do |product|
        # add product sold status and probably id to products_sold_statuses
      end
      render :json => product_sold_statuses, :layout => false
    end
  end
end

That code isn't tested so just use it as a base on building the solution. It also assumes you're using JQuery.

Upvotes: 0

nurettin
nurettin

Reputation: 11736

There are many methods for getting server updates.

  • Polling (setTimeout to make an ajax request every so often)
  • Long Polling (what facebook uses)
  • Comet (Blocking the request, not letting it finish while injecting javascript periodically, similar to long polling)
  • WebSockets (html5 stuff)
  • Flash/Java applet etc.

Usually a simple polling-every-so-many-seconds will do the job. -> (asciicast)

Here is a comparison of different methods.

Upvotes: 1

Related Questions