【问题标题】:before_filter and Ajax Rails 4before_filter 和 Ajax Rails 4
【发布时间】: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


    【解决方案1】:

    当某些东西被添加到购物车时,您可以绑定到一个 jQuery click 事件,然后返回您想要更新的值并使用 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返回新值。

    【讨论】:

      猜你喜欢
      • 2013-05-07
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      相关资源
      最近更新 更多