Skip to content

Instantly share code, notes, and snippets.

@Lumbe
Created March 17, 2017 15:41
Show Gist options
  • Save Lumbe/40d8690cd0560cbfb6afce8087ff18d2 to your computer and use it in GitHub Desktop.
Save Lumbe/40d8690cd0560cbfb6afce8087ff18d2 to your computer and use it in GitHub Desktop.
rails ajax example

Ruby on Rails Ajax example

  1. Add remote: true option to link, button or form
# app/views/products/show.html.haml

button_to 'Add to Cart', line_items_path(product_id: product), remote: true
  1. Stop the create action from redirecting to the index display if the request is for JavaScript. We do this by adding a call to respond_to() telling it that we want to respond with a format of .js:
# app/controllers/line_items_controller.rb
def create
  product = Product.find(params[:product_id])
  @line_item = @cart.add_product(product)
  respond_to do |format|
    if @line_item.save
      format.html { redirect_to store_index_url }
➤    format.js
      format.json { render :show,
      status: :created, location: @line_item }
    else
      format.html { render :new }
      format.json { render json: @line_item.errors,
      status: :unprocessable_entity }
    end
  end
end
  1. Rails supports templates that generate JavaScript—the js stands for JavaScript. A .js.erb template is a way of getting JavaScript on the browser to do what you want, all by writing server-side Ruby code. Let’s write our first: create.js.erb. It goes in the app/views/line_items directory, like any other view for line items:
# app/views/line_items/create.js.erb
$('#cart').html("<%=j render(@cart) %>");         # renders app/views/carts/_cart.html.erb

This simple template tells the browser to replace the content of the element whose id is cart with that HTML.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment