[英]Ruby on rails Stripe - set default amount to shopping cart subtotal
我試圖將購物車連接到Stripe,並將金額設置為購物車的訂單小計。 我嘗試在訂單模型中定義order_subtotal,並嘗試通過條碼中的amount字段傳遞它,但在結帳時出現以下錯誤:無效的整數:order_subtotal
我找不到任何在線內容來解釋如何使用紅寶石語言連接不同數量的條紋。 任何幫助將不勝感激,謝謝!
charges_controller.rb
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
@amount = :order_subtotal
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => :order_subtotal,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end end
cart / show.html.erb
<div class="shopping-cart"> <%= render "shopping_cart" %> <%= form_tag charges_path do %> <article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
<label class="amount">
<span>:order_subtotal</span>
</label> </article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key=ENV[PUBLISHABLE_KEY]
data-description="Checkout"
data-amount= "amount"
data-locale="auto"
data-shipping-address="null"
> </script>
<% end %> </div>
_shopping_cart.html.erb
<% if !@order_item.nil? && @order_item.errors.any? %>
<div class="alert alert-danger">
<ul>
<% @order_item.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% if @order_items.size == 0 %>
<p class="text-center">
There are no items in your shopping cart. Please <%= link_to "go back", root_path %> and add some items to your cart.
</p>
<% else %>
<% @order_items.each do |order_item| %>
<%= render 'carts/cart_row', product: order_item.product, order_item: order_item, show_total: true %>
<% end %>
<p class="text-center">Order SubTotal=<%= order_subtotal= @order_items.sum(:total_price)%></p>
<% end %>
order.rb
class Order < ActiveRecord::Base
belongs_to :order_status
has_many :order_items
before_create :set_order_status
before_save :update_subtotal
def subtotal
order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0}.sum
end
def order_subtotal
@order_items.sum(:total_price) end end private def set_order_status
self.order_status_id = 1 end
def update_subtotal
self[:subtotal] = subtotal end
在您的charges_controller.rb
替換
:amount => :order_subtotal
與
:amount => order_subtotal
您要添加符號而不是order_subtotal
方法的結果。
同樣在您的cart / show.html.erb中,您可能想要
<span><%= order_subtotal %></span>
代替
<span>:order_subtotal</span>
關於這條線:
<p class="text-center">Order SubTotal=<%= order_subtotal= @order_items.sum(:total_price)%></p>
由於在為購物車Order#order_subtotal
時似乎沒有訂單實例,因此無法訪問Order#order_subtotal
方法。 因此,最好是使用諸如cart_subtotal
類的輔助方法來計算顯示的值,而不是直接在模板中執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.