Updating Quantities & Prices with AJAX

Free Ruby on Rails Tutorial

Dive into this comprehensive tutorial on implementing AJAX in Rails, featuring a mix of other Rails features including web services and email, as we navigate through hands-on exercises and practical application.

This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics covered in this Ruby on Rails tutorial:

Adding an AJAX request

Exercise Overview

In this section, we will be looking at a hodgepodge of Rails features including AJAX, web services, and email. First, in this exercise, we’ll see how easy it is to implement AJAX in Rails.

  1. If you completed the previous exercises, you can skip the following sidebar. We recommend you finish the previous exercises (8A-10B) before starting this one. If you haven’t finished them, do the following sidebar.

    If You Did Not Do the Previous Exercises (8A-10B)

    1. Close any files you may have open.
    2. Open the Finder and navigate to Class Files > yourname-Rails Class
    3. Open Terminal.
    4. Type cd and a single space (do NOT press Return yet).
    5. Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
    6. Run rm -rf nutty to delete your copy of the nutty site.
    7. Run git clone https://bitbucket.org/noble-desktop/nutty.git to copy the That Nutty Guy git repository.
    8. Type cd nutty to enter the new directory.
    9. Type git checkout 10B to bring the site up to the end of the previous exercise.
    10. Run bundle to install any necessary gems.
    11. Run yarn install --check-files to install JavaScript dependencies.

Getting Started

  1. For this exercise, we’ll continue working with the nutty folder located in Desktop > Class Files > yourname-Rails Class > nutty.

    If you haven’t already done so, we suggest opening the nutty folder in your code editor if it allows you to (like Sublime Text does).

  2. Run ‘yarn add jquery’

  3. You should still have a window with two tabs open in Terminal from the last exercise, the first of which is running the server. If you don’t, complete the following sidebar.

    Restarting the Rails Server

    1. In Terminal, cd into the nutty folder:
    • Type cd and a space.
    • Drag the nutty folder from Desktop > Class Files > yourname-Rails Class onto the Terminal window (so it will type out the path for you).
    • In Terminal, hit Return to change directory.
    1. In Terminal, type the following:

      rails s
      
    2. Open a new tab (Cmd–T) leaving our server running in the old tab.
    3. In the new tab, cd into the nutty folder:
    • Type cd and a space.
    • Drag the nutty folder from Desktop > Class Files > yourname-Rails Class onto the Terminal window (so it will type out the path for you).
    • In Terminal, hit Return to change directory.
  4. In the browser navigate to: localhost:3000

    If you see a Sign Out link at the top right, you are already signed in and you can skip the next step. The sign in instructions differ based on if you already have login info.

  5. If you already have a username and password: At the top right, click Sign In and sign in with the email and password you’ve been using.

    If you started from a prepared folder and don’t have an account: Click the Sign up link, enter an email and password, then click Sign Up.

  6. Click on a product.

  7. Click Add To Cart.

  8. Notice there is an update button below the product quantity.

    We’re going to use this button to get a bit of AJAX functionality into our site. Rather than reloading the entire page when the update button is clicked, we only want to reload and recalculate the elements that change (Total Price, Subtotal, and Total).

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Making the Update Link Functional

Let’s start by adding this functionality to our cart view.

  1. In your code editor, open nutty > app > views > cart > index.html.erb

  2. Around line 35, find the update link wrapped in an <a> tag. We need to make a form tag so we can submit the quantity field along with the form submission.

  3. Wrap it in a form tag by adding the following bold code starting around line 34:

    <td>
       <%= form_with model: line_item, method: :patch, local: false do |f| %>
          <%= f.number_field :quantity, min: 1, max: 100 %>
          <a href="#">update</a>
       <% end %>
       <%= link_to 'remove', line_item_path(line_item), method: :delete %>
    
  4. Let’s break down that code:

    • line_item refers to the specific line item in question.
    • method: :patch calls the update method by default—exactly what we want because we’re not creating or deleting a line item, just updating an existing one.
    • local: false is what makes this an AJAX request. It’s probably the most important piece, as Rails will do a bunch of stuff behind the scenes because of it.
  5. We need to make the update link into a button. Starting around line 36, delete the <a> tags and replace them with the following bold code:

       <%= f.number_field :quantity, min: 1, max: 100 %>
       <%= f.submit %>
    <% end %>
    

    NOTE: Although this new link will behave more like a button, we’re basically styling it to look like a link so it looks correct in the context of the page’s design.

  6. Save the file and leave it open.

  7. In your code editor, open nutty > app > controllers > line_items_controller.rb

  8. Add the update method before the destroy method around line 15:

    end
    
    def update
       @line_item = LineItem.find(params[:id])
       @line_item.update(params.require(:line_item).permit(:quantity))
       @line_item.save
    end
    
    def destroy
    
  9. Save the file and close it.

  10. Put an item in the cart and try adjusting its quantity. Nothing seems to change, but if we reload the cart page, we’ll see the adjusted quantity. Fixing that is where Rails’s AJAX powers will come in.

Fixing the Total Price

So what’s the next step? Ordinarily, we would write some kind of view to render something from our controller. We’re using AJAX instead of rendering HTML, so we need to create a file where we can embed Ruby code in with some JavaScript.

  1. Switch back to your code editor.

  2. Create a new file.

  3. Save it as update.js.erb into the nutty > app > views > line_items folder.

    Creating this file gives us the ability to return JavaScript that will execute after the AJAX command.

  4. Test that JavaScript is working before we go any further. Type:

    alert('<%= @line_item.title %>');
    
  5. Save the file and leave it open.

  6. Go to the browser and reload the cart: localhost:3000/cart

  7. Change the Quantity of a product, then click update.

    An alert should pop up with the title of the item. One nice thing is that we’re able to pass Ruby code into our JavaScript.

  8. Click OK to dismiss the alert. Great, our code is working so far!

  9. Go back to update.js.erb and delete the alert code.

  10. Let’s try manipulating the Total Price field. Type:

    $('td.total-price').html('<%= number_to_currency @line_item.subtotal %>');
    
  11. Save the file.

  12. Go to the browser and navigate to: localhost:3000

  13. Add another product to your cart.

  14. Change the Quantity of a product, then click update.

    Hmm, notice that the Total Price changed for all items instead of just the one. It’s because we aren’t being specific enough in our JavaScript. Every line item is getting updated, so we need to make each line item unique.

    Let’s try using some unobtrusive JavaScript. Unobtrusive JavaScript is a new best practice technique, which uses data hooks instead of ordinary HTML tags in order to keep back-end logic separate from front end design.

  15. In your code editor, open nutty > app > views > cart > index.html.erb

  16. Around line 45, add the following bold code:

    <td class="total-price" data-line-item-id="<%= line_item.id %>"><%= number_to_currency line_item.subtotal %></td>
    
  17. Save the file.

  18. In your code editor, open nutty > app > views > line_items > update.js.erb

  19. Replace .total-price with the code shown in bold:

    $('td[data-line-item-id=<%= @line_item.id %>].total-price').html('<%= number_to_currency @line_item.subtotal %>');
    
  20. Save the file.

  21. Go to the browser and reload the cart: localhost:3000/cart

  22. Change the Quantity of a product, then click update.

    Now only that one product’s price will change. Let’s get the Subtotal and Total fields in the Order Summary section working as well.

Fixing the Subtotal & Total

  1. In your code editor, open nutty > app > views > cart > index.html.erb

  2. Around line 59, add the following bold code:

       <td>Subtotal</td>
       <td id="subtotal"><%= number_to_currency @cart.subtotal %></td>
    </tr>
    
  3. Around line 71, add the following bold code:

       <td>Total</td>
       <td id="total"><%= number_to_currency @cart.total %></td>
    </tr>
    
  4. Save the file.

  5. In your code editor, open nutty > app > views > line_items > update.js.erb

  6. On the second line, add the following bold code:

    $('td[data-line-item-id=<%= @line_item.id %>]').html('<%= number_to_currency @line_item.subtotal %>');
    $('td#subtotal').html('<%= number_to_currency @cart.subtotal %>');
    $('td#total').html('<%= number_to_currency @cart.total %>');
    

    NOTE: Remember that @cart is an instance variable already created by our before action, load_cart_or_redirect_customer.

  7. Save the file.

  8. Go to the browser and reload the cart: localhost:3000/cart

  9. Change the Quantity of a product, then click update.

    Now all the Totals should be working perfectly! Rock on!

  10. Leave Terminal, your code editor, and browser open as we will continue to work with them in the following exercise.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram