我有一个应用程序,我正在测试条带付款。现在,我正在尝试配置费用,以便从另一个模型(pin.price)中获取价格并正确收费。到目前为止,我遇到以下错误消息:
ChargesController中的NoMethodError #create 未定义的方法`price'为nil:NilClass
应用程序/控制器/ charges_controller.rb
class ChargesController < ApplicationController
def create
# Amount in cents
@amount = (@pin.price * 100).floor
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
end
应用程序/控制器/ pins_controller.rb
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy, :bid]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
.....
def pin_params
params.require(:pin).permit(:description, :price, :image, :manufacturer, :model)
end
end
应用程序/分贝/迁移
class AddPriceToPins < ActiveRecord::Migration
def change
add_column :pins, :price, :decimal
end
end
我很确定这个错误来自“@amount =(@ pin.price * 100).floor”,但我不知道如何更好地表达这个数量,所以每个引脚的价格都不是静态但匹配到数据库中当前输入的值。
编辑:在此处包含带条带付款代码链接的表单:
<%= form_tag charges_path, id: 'chargesForm' do %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<%= hidden_field_tag 'stripeToken' %>
<%= hidden_field_tag 'stripeEmail' %>
<button id="btn-buy" type="button" class="btn btn-success btn-lg btn-block"><span class="glyphicon glyphicon-heart"></span> I want this!</button>
<script>
var handler = StripeCheckout.configure({
key: '<%= Rails.configuration.stripe[:publishable_key] %>',
token: function(token, arg) {
document.getElementById("stripeToken").value = token.id;
document.getElementById("stripeEmail").value = token.email;
document.getElementById("chargesForm").submit();
}
});
document.getElementById('btn-buy').addEventListener('click', function(e) {
handler.open({
name: '<%= @pin.manufacturer %>',
description: '<%= @pin.description %>',
amount: '<%= (@pin.price * 100).floor %>'
});
e.preventDefault();
})
</script>
<% end %>
有什么想法吗?
答案 0 :(得分:1)
问题在于,您的费用控制器@pin
未分配给任何内容,因此其值为nil
,因此出现错误。
因此,您需要在价格之前为其分配@pin
。为了做到这一点,你需要弄清楚如何从数据库获取引脚或者是否创建引脚。
一种解决方案可能是在请求路径中传入引脚的id,例如
create_charge_path(pin_id: 123)
编辑:这不必硬编码到123它可以是你喜欢的任何引脚,只取决于它被调用的位置。例如。如果您从另一个已从数据库加载特定引脚的控制器操作调用,则可以执行以下操作:
create_charge_path(pin_id: pin.id)
然后在ChargesController
class ChargesController < ApplicationController
def create
@pin = Pin.find(params[:pin_id])
# Amount in cents
@amount = (@pin.price * 100).floor
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
end
然后,这会将@pin
分配给数据库ID为123
的图钉。