我正在使用rails构建一个事件应用程序,我在预订确认过程结束时遇到了上述错误。这是完整的错误 -
这是我的控制器代码 -
预订控制器
class BookingsController < ApplicationController
before_action :authenticate_user!
def new
@event = Event.find(params[:event_id])
# and because the event "has_many :bookings"
@booking = Booking.new(params[:booking])
@booking.user = current_user
end
def create
@event = Event.find(params[:event_id])
@booking = @event.bookings.new(booking_params)
@booking.user = current_user
if
@booking.booking
flash[:success] = "Your place on our event has been booked"
redirect_to event_booking_path(@event, @booking)
else
flash[:error] = "Booking unsuccessful"
render "new"
end
if @event.is_free?
@booking.save(booking_params)
end
end
def show
@event = Event.find(params[:event_id])
@booking = Booking.find(params[:id])
end
def update
if @booking.update(booking_params)
redirect_to event_booking_path(@event, @booking) , notice: "Booking was successfully updated!"
else
render 'new'
end
end
private
def booking_params
params.require(:booking).permit(:stripe_token, :booking_number, :quantity, :event_id, :stripe_charge_id, :total_amount)
end
end
我正在尝试实施代码来处理免费和付费活动/预订。活动方面很好,但处理免费预订已证明很麻烦。这是预订型号代码 -
Booking.rb
class Booking < ActiveRecord::Base
belongs_to :event
belongs_to :user
before_create :set_booking_number
validates :quantity, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :total_amount, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :quantity, :total_amount, :booking_number, presence: true
def set_booking_number
self.booking_number = "MAMA" + '- ' + SecureRandom.hex(4).upcase
end
def booking
# Don't process this booking if it isn't valid
#self.valid?
if self.event.is_free?
self.total_amount = 0
else
begin
self.total_amount = event.price_pennies * self.quantity
charge = Stripe::Charge.create(
amount: total_amount,
currency: "gbp",
source: stripe_token,
description: "Booking created for amount #{total_amount}")
self.stripe_charge_id = charge.id
self.booking_number = "MAMA" + '- ' + SecureRandom.hex(4).upcase
save!
rescue Stripe::CardError => e
errors.add(:base, e.message)
false
end
end
#end
end
end
此问题出现在包含验证之后 - 问题一直在尝试实施适用于付费事件但不是免费的验证。
对上述错误的任何帮助都将不胜感激。
答案 0 :(得分:0)
您需要使用正确的路线
Rails期待:id
而不是:event_id
所以,如果你使用的是宁静的路线
将网址用作booking_path(7)
而不是booking_path(event_id: 7)
或将您的路线更改为
get 'bookings/:event_id', to: 'bookings#show'
答案 1 :(得分:0)
尝试替换
redirect_to event_booking_path(@event, @booking)
与
redirect_to event_booking_path(id: @booking.id, event_id: @event.id)
<强>更新强>
我认为错误是因为@booking.id
正在评估nil
。它会发生@booking
没有保存到db(仍然是新记录)。在模型方法booking
中,在if
块内,您只是设置属性,但不保存对象。因此,在设置属性后调用save!
块内的if
应解决此问题。
def booking
if self.event.is_free?
self.total_amount = 0
save!
else
...
end
end