before_filter和Ajax Rails 4

时间:2016-03-02 13:40:23

标签: jquery ruby-on-rails ruby ajax ruby-on-rails-4

我正在重构一些代码,并认为每个控制器中使用的方法现在拥有它自己的类,并使用应用程序控制器中的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

的新实例

1 个答案:

答案 0 :(得分:0)

当某些内容添加到购物车后,您可以绑定到jQuery点击事件,然后返回您想要更新的值,只需使用jquery更改它。

 $.ajax({
   type: 'GET', // or whatever you make the route in the controller
   url: "/whatever/route_you_create"
   data: "value to add to existing"
 }).done(function(ajax_response){
   // set .val(ajax_response['num_to_change']) 
 })

更新控制器操作中的值并保存新值,然后通过json返回新值。