[/code] 效率不高啊, :shock: ,看来还是要提高效率。要专注,要心无房屋。
这节主要是用helper隐藏作侧边栏的购物车,如果没有东西时,隐藏购物车,有东西时渐进显示,突然显示出来,会吓坏小朋友的,所以我们要慢慢的显示出来。
判断购物车首先不为空 <%unless @cart.items.emtpy? ... end%>
给购物车加上渐进效果,同样是用Ajax。
在view/store/add_to_cart.js.rjs 加一下内容
page[:cart].visual_effect :blind_down if @cart.total_items == 1
toal_item定义在model/cart.rb下
[code="ruby"]
def total_items
@items.sum{|item|item.quantity}
end
接下来,当购物车为空的时候,不显示,通常是加上一个style display:none
如一般写法。
<div id="cart"<%if @cart.items.empty? %>
style="display:none"
<% end %>
>
</div>
太难看了,而且也容易出错,比如右边尖括号,。
rails 提供了helper 处理 view。[color=red]helper可以抽象出view里面的一些过程(直译),那partial处理逻辑/数据,是这样分工么?什么时候用哪个[/color]
一个controller默认生成一个helper.
编辑view/layouts/store.html.erb
<div id="cart">
<%hidden_div_if(@cart.items.empty?,:id => "cart") do%>
<%= render (:partial => "cart",:object => @cart)%>
<% end %> #为什么用 do end 多行rails
</div>
在StoreHelper定义hidden_div_if
module StoreHelper
def hidden_div_if(condition,attributes = {},&block)
if condition
attributes['style'] = "disaply:none"
end
content_tag("div",attributes,&block)
end
end
content_tag(name,content_or_option,option),&block把hidden_div_if传递给content_tag
最后改一点,判断是否使用js.rails用xhr缩写代表XMLHttpRequest。用 if request.xhr?判断是否使用js
if request.xhr?
respond_to{|format| format.js}
else
redirect_to_index
end