- 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
- 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
- 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.