私はRuby on Railsを使ってイベントアプリを構築しています。私はイベントが過大予約にならないように予約するためのシステムを作成する必要があります。各イベントには利用可能なスペースが限られています。たとえば、100スペースが利用可能な場合、105の予約は行われません。Rails - イベントが過剰登録されないようにする
これまでの私の考えですが、私が試したが実際には働いていないコードもあります。
bookings_controllerビューで
def create
@event = Event.find(params[:event_id)
if @event.bookings.count >= @event.total_spaces
flash[:warning] = "Sorry, this event is fully booked."
redirect_to root_path
else
#code to save the booking
end
end
-
<% if @event.bookings.count > @event.total_spaces %>
# flash: "This event is fully booked"
<% else %>
# code to make the booking
私はこれが私の目標を達成するのに十分であるかわかりません。私は予約モデルとこれをカバーするいくつかの検証でより堅牢なメソッドが必要ですか?
私は、トランザクションコードブロックしようとした -
Booking.transaction do
@event.reload
if @event.bookings.count > @event.number_of_spaces
flash[:warning] = "Sorry, this event is fully booked."
raise ActiveRecord::Rollback, "event is fully booked"
end
end
をそれはまだトランザクションが完了した後のフラッシュメッセージが&を示した前にユーザーが支払いを処理することができて、それは動作しませんでした。
私は少し前倒しされる前にこのようなものを作ったことはありません。任意の指導、感謝します。
UPDATE - すべての
Booking.rb
def set_booking
return {result: false, flash: :warning, msg: 'Sorry, this event is fully booked'} if event.bookings.count >= event.total_spaces
if self.event.is_free?
self.total_amount = 0
save!
else
self.total_amount = event.price_pennies * self.quantity
begin
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
save!
rescue Stripe::CardError => e
# if this fails stripe_charge_id will be null, but in case of update we just set it to nil again
self.stripe_charge_id = nil
# we check in validatition if nil
end
end
{result: true, flash: :success, msg: 'Booking successful!'}
エンド
bookings_conroller.rb
def create
# actually process the booking
@event = Event.find(params[:event_id])
# as above, the association between events and bookings means -
@booking = @event.bookings.new(booking_params)
@booking.user = current_user
handler = BookingHandler.new(@event)
booking = handler.set_booking(booking_params)
flash[booking[:flash]] = booking[:msg]
redirect_to root_path
# rest of controller code for booking
http://stackoverflow.com/help/how-to-askをお読みください。あなたが特定の問題に絞って、より明確にあなたの意図を説明し、人々があなたを簡単に助けることができるなら、それは良いでしょう。 –
それに応じて私は改正する。私はイベントが利用可能なスペースの数を超えて予約を取らないことを保証しようとしています。あなたはこれを手伝うことができますか? –
どのような方法を使用していても、レースコンディションを避けるためにイベントに人を追加するアクティビティをロック/シリアライズする方法が必要です –