一。把JavaScript库发送到用户的浏览器
app\views\layouts\store.rhtml
< title > Pragprog Books Online Store </ title >
<% = stylesheet_link_tag ' depot' ,:media=>"all"%>
< % = javascript_include_tag :defaults %>
</ head >
二。把button_to 方法修改成form_remote_tag方法
1.注:此处书本代码写错了
app\views\store\index.rhtml
<% for product in @products - %>
< div class ="entry" >
< img src ="<%=product.image_url %>" />
< h3 > <% = h(product.title) %> </ h3 >
<% = product.description %>
< div class ="price-line" >
< div class ="price" > <% = number_to_currency(product.price) %> </ div >
<% form_remote_tag :url => {:action => :add_to_cart,:id => product} do %>
<% = submit_tag " Add to Cart " %>
<% end %>
</ div >
</ div >
<% end %>
2.修改add_to_cart方法,使只在JavaScript被禁用的时候才转移到主页
app\controllers\store_controller.rb
begin
@product = Product . find(params[ : id])
rescue ActiveRecord :: RecordNotFound
logger . error( " Attempt to access invalid product #{params[:id]} " )
redirect_to_index( " Invalid product " )
else
@cart = find_cart
@current_item = @cart . add_product(@product)
redirect_to_index unless request .xhr?
end
end
3.创建app\views\store\add_to_cart.rjs(记住要删除add_to_cart.rhtml)
三。高亮
1.把current_item赋值给控制器的实例变量@current_item
(1)修改app\models\cart.rb,使返回current_item
current_item = @items . find{ | item | item . product == product}
if current_item
current_item . increment_quantity
else
current_item = CartItem . new (product)
@items << current_item
end
current_item
end
(2)修改store_controller.rb,把从add_product获得的current_item赋值给实例变量@current_item
begin
@product = Product . find(params[ : id])
rescue ActiveRecord :: RecordNotFound
logger . error( " Attempt to access invalid product #{params[:id]} " )
redirect_to_index( " Invalid product " )
else
@cart = find_cart
@current_item = @cart. add_product(@product)
redirect_to_index unless request . xhr ?
end
end
2.\views\store\_cart_item.rhtml局部模板中给current_item做标记
<tr id = "current_item">
<% else %>
<tr>
<% end %>
< td > <% = cart_item.quantity %> × </ td >
< td > <% = h(cart_item.title) %> </ td >
< td class ="item-price" > <% = number_to_currency(cart_item.price) %> </ td >
</ tr >
3.利用current_item标记,在add_to_cart.rjs模板中调用visual_effect方法
page[ : current_item] . visual_effect : highlight ,
: startcolor => " #88ff88 " ,
: endcolor => " #114411 "
四。隐藏空购物车
1.显示刚创建的购物车
store\add_to_cart.rjs
page[ :cart].visual_effect :blind_down if @cart.total_items ==1
page[ : current_item] . visual_effect : highlight ,
: startcolor => " #88ff88 " ,
: endcolor => " #114411 "
models\cart.rb添加total_items方法
@items . sum { | item | item . quantity}
end
2.辅助方法修改购物车CSS的id
(1)在helpers\store_helper.rb创建辅助方法
def hidden_div_if(condition , attributes = {} )
if condition
attributes[ " style " ] = " display :none "
end
attrs = tag_options(attributes . stringify_keys)
" <div #{attrs}> "
end
end
(2)在布局模板中调用辅助方法
<% = render(:partial => " cart " , : object => @cart) %>
</ div >
3.修改控制器,去除清空提示
store_controller.rb
session[:cart] = nil
redirect_to_index
end