[英]before_filter and Ajax 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)'%>
因此,當將商品添加到購物create.js.erb
我通過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
的值以進行更新
我可能沒有想到明顯的東西
謝謝
更新
我想我已經解決了,但是它是否是我不知道的正確解決方案,在添加我的create controller內引起別人的想法很有趣
@user_subtotal = UserSubtotal::Subtotal.new(current_or_guest_user).subtotal if request.xhr?
這給了我@user_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返回新值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.