【发布时间】:2016-03-02 13:40:23
【问题描述】:
我正在重构一些代码,并认为在每个控制器中使用的方法现在都有自己的类,并在应用程序控制器中使用 before_filter 调用
class ApplicationController < ActionController::Base
before_filter :subtotal
def subtotal
@user_subtotal = UserSubtotal::Subtotal.new(current_or_guest_user).subtotal
end
end
class UserSubtotal::Subtotal
def initialize(user)
@user = user
end
def subtotal
@frame_total = CartItem.frame_price_total(@user)
@image_size_total = CartItem.image_size_price_total(@user)
@subtotal = CartItem.subtotal(@frame_total, @image_size_total)
end
end
在我看来,我正在渲染一个部分(它跟踪用户购物车小计)
<span class="total"><%= render 'shared/cart_amount' %></span>
_cart_amount.html.erb
<%= number_to_currency(@user_subtotal, unit: '£') + ' (excluding shipping)'%>
因此,当我将商品添加到购物车时,我通过 Ajax 执行此操作,create.js.erb 文件呈现相同的部分
create.js.erb
$(".total").html('<%= j render partial: "shared/cart_amount" %>');
cart_items_controller
def create
respond_to do |format|
if @cart_item.save
format.js { flash.now[:success] = 'Successfully added to cart' }
else
format.js { flash.now[:error] = @cart_item.errors.full_messages }
end
end
end
在这种情况下如何获取@user_subtotal 的值来更新
我可能没有想到明显的东西
谢谢
更新
我想我解决了它,但它是否是我不知道的正确解决方案,有趣的是让其他人的想法,在我添加的创建控制器中
@user_subtotal = UserSubtotal::Subtotal.new(current_or_guest_user).subtotal if request.xhr?
这给了我一个 @user_subtotal 的新实例
【问题讨论】:
标签: jquery ruby-on-rails ruby ajax ruby-on-rails-4