【问题标题】:Rails / Stripe - undefined method `stripe_token' for nil:NilClassRails / Stripe - nil:NilClass的未定义方法`stripe_token'
【发布时间】:2017-01-24 20:22:54
【问题描述】:

我在我的 Rails 应用程序上使用 Stripe 进行付款,但遇到了上述错误。我最近将大部分代码从我的控制器移动到模型,这是我第一次遇到这个错误(我之前测试过付款,但从未出现过)。不太清楚为什么现在会出现这种情况。

这是我的模型代码 -

Booking.rb

class Booking < ActiveRecord::Base

    belongs_to :event
    belongs_to :user

    def reserve
    # Don't process this booking if it isn't valid
    return unless valid?

    # We can always set this, even for free events because their price will be 0.
    self.total_amount = quantity.to_i * event.price_pennies.to_i

    # Free events don't need to do anything special
    if event.is_free?
      save

    # Paid events should charge the customer's card
    else
      begin
        charge = Stripe::Charge.create(amount: total_amount, currency: "gbp", card: @booking.stripe_token, description: "Booking number #{@booking.id}", items: [{quantity: @booking.quantity}])
        self.stripe_charge_id = charge.id
        save
      rescue Stripe::CardError => e
        errors.add(:base, e.message)
        false
      end
     end 
  end
end

在我的控制器中 -

bookings_controller.rb

def create
    # actually process the booking
    @event = Event.find(params[:event_id])
    @booking = @event.bookings.new(booking_params)
    @booking.user = current_user

        if @booking.reserve
            flash[:success] = "Your place on our event has been booked"
            redirect_to event_path(@event)
        else
            flash[:error] = "Booking unsuccessful"
            render "new"
        end
    end

这是错误信息 -

我对 Rails 很陌生,如果这看起来很简单,我们深表歉意,我们将不胜感激。

【问题讨论】:

  • 您能否发布实际的错误消息,以便我们知道它发生在哪一行代码上?如果它在模型文件中,在开始/救援块中,我看不到您在哪里定义了 @booking 对象。
  • 我已经添加了错误信息。

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller stripe-payments


【解决方案1】:

@booking 是一个实例变量,仅在控制器/视图的上下文中可用。由于reserve 是模型上的一个实例方法,你可能只想引用self 或什么都不引用,即@booking.method => self.methodmethod

【讨论】:

  • 所以,我只输入 'total_amount' 或 'self.total_amount' ?
猜你喜欢
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 1970-01-01
  • 2014-11-23
  • 2012-09-25
  • 1970-01-01
相关资源
最近更新 更多