0

I'm building an events site using Rails and I'm not sure whether my database is capturing bookings as they happen. I'm still in development mode so any bookings are purely 'mock' for demo purposes. How do I check whether they're being logged ( I'm pretty sure they're not) and if they're not - how do I remedy this?

Here's the relevant code as things stand -

booking.rb

class Booking < ActiveRecord::Base

belongs_to :event
belongs_to :user

end

bookings_controller.rb

class BookingsController < ApplicationController

before_action :authenticate_user!

def new
    @event = Event.find(params[:event_id])
    @booking = @event.bookings.new
    # which person is booking the event?
    @booking.user = current_user
    @booking.quantity = @booking.quantity
    @total_amount = @booking_quantity.to_f * @event_price.to_f

end

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


    if @booking.save


        Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",
            card: @booking.stripe_token, description: "Booking number #{@booking.id}")

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

    if @event.is_free?

        flash[:success] = "Your place on our event has been booked"
        redirect_to event_path(@event)
    end
end

private

def booking_params
    params.require(:booking).permit(:stripe_token, :quantity)
end



end

schema.rb

create_table "bookings", force: :cascade do |t|
t.integer  "event_id"
t.integer  "user_id"
t.string   "stripe_token"
t.datetime "created_at",   null: false
t.datetime "updated_at",   null: false
t.integer  "quantity"

Do I need to add a booking_id to the bookings table?

Mike.Whitehead
  • 798
  • 18
  • 52

1 Answers1

0

I'm assuming you created the bookings schema using a migration. If that's not the case, please consider using it.

There's no need to explicitly add a booking_id column, rails will add it. About making sure the record gets saved, you can use a begin/rescue clause:

begin
  @booking.save!
rescue
  # error handling code
end

You can also use the rails console to see what's the last Booking record in the database.

$ rails c --sandbox
>> Booking.last

I hope that helps.

Community
  • 1
  • 1
  • Many thanks. Yes, I used a migration. A booking id would be useful anyway, though, to provide to people when they book on to events? – Mike.Whitehead Jul 08 '16 at 22:29
  • Then call it `booking_number`, as your actual message calls it. This would prevent the confusion between technical ids and user-facing tokens. – Nic Nilov Jul 09 '16 at 11:05
  • I agree, the `booking_id` exists but the users shouldn't know your apps internals, a `booking_number` should be a safer option. – Jesús Abarca Jul 10 '16 at 14:36