12.1 Iteration H1: Capturing an Order 11.4 Iteration F4: Hide an Empty Cart
create a channel
rails generate channel products
create app/channels/products_channel.rb
identical app/assets/javascripts/cable.js
create app/assets/javascripts/channels/products.coffee
create a channel
edit app/channels/products_channel.rb
class ProductsChannel < ApplicationCable::Channel
def subscribed
stream_from "products"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
Update price when notified of price changes
edit app/assets/javascripts/channels/products.coffee
App.products = App.cable.subscriptions.create "ProductsChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
$(".store #main").html(data.html)
send updates when price changes
edit app/controllers/products_controller.rb
def update
respond_to do |format|
if @product.update(product_params)
format.html { redirect_to @product,
notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: @product }
@products = Product.all
ActionCable.server.broadcast 'products',
html: render_to_string('store/index', layout: false)
else
format.html { render :edit }
format.json { render json: @product.errors,
status: :unprocessable_entity }
end
end
end
Run tests
rails test
Run options: --seed 64579
# Running:
...............................
Finished in 1.044873s, 29.6687 runs/s, 63.1656 assertions/s.
31 runs, 66 assertions, 0 failures, 0 errors, 0 skips
Save our progress
git commit -a -m "AJAX"
[master cdfab4c] AJAX
6 files changed, 60 insertions(+), 22 deletions(-)
rewrite app/assets/javascripts/application.js (61%)
git tag iteration-f
12.1 Iteration H1: Capturing an Order 11.4 Iteration F4: Hide an Empty Cart