我試圖讓用戶一次爲多個空間預訂事件,因此如果一個事件中的一個空間花費£10而用戶想要預訂四個空間,那麼他們需要支付40英鎊。 我已經實現了一個方法,我的預訂模式,以應付這一點 -Rails-如何在數量模型中設置默認值
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 * event.price_pennies
# 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
當我嘗試處理預約我碰到下面的錯誤 -
NoMethodError in BookingsController#create 未定義方法`*'爲零:NilClass
這行代碼被突出顯示 -
self.total_amount = quantity * event.price_pennies
我需要檢查/確保數量返回1或更大的值,並且event.price_pennies返回0(如果它是免費事件)並且如果它是付費事件返回大於0。我該怎麼做呢?
我沒有在我的遷移中爲數量設置任何默認值。我schema.rb文件顯示本作price_pennies -
t.integer "price_pennies", default: 0, null: false
這是什麼在我的控制器創建 -
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
所以,我需要一種方法我的預訂模式,以糾正這一點,或者我應該做一個數量驗證和before_save回調事件?
我不太清楚如何做到這一點,所以任何援助將不勝感激。
但是,他們已經是整數?這將如何改變事情? –
想要嘗試一下嗎?聽起來像'數量'也可能是'無'。 – mudasobwa
是的,我認爲這是,我如何設置模型中數量的默認值?我在遷移時沒有設置任何內容,它需要爲1或更多。 –