Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 在过滤器和Ajax Rails 4之前_Jquery_Ruby On Rails_Ruby_Ajax_Ruby On Rails 4 - Fatal编程技术网

Jquery 在过滤器和Ajax Rails 4之前

Jquery 在过滤器和Ajax Rails 4之前,jquery,ruby-on-rails,ruby,ajax,ruby-on-rails-4,Jquery,Ruby On Rails,Ruby,Ajax,Ruby On Rails 4,我正在重构一些代码,我认为每个控制器中使用的方法现在都有自己的类,并在应用程序控制器中使用before_过滤器调用 class ApplicationController < ActionController::Base before_filter :subtotal def subtotal @user_subtotal = UserSubtotal::Subtotal.new(current_or_guest_user).subtotal end end cl

我正在重构一些代码,我认为每个控制器中使用的方法现在都有自己的类,并在应用程序控制器中使用before_过滤器调用

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
购物车项目\u控制器

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\u subtotal
的值

我可能没有想到什么显而易见的事情

谢谢

更新

我想我解决了这个问题,但我不知道这是否是正确的解决方案,在我添加的create controller中,有趣的是能让其他人产生想法

@user_subtotal = UserSubtotal::Subtotal.new(current_or_guest_user).subtotal if request.xhr?

这给了我一个新的
@user\u subtotal

实例,当有东西添加到购物车时,您可以绑定到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返回新值

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 = UserSubtotal::Subtotal.new(current_or_guest_user).subtotal if request.xhr?
 $.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']) 
 })