Rails - 将预订保存到数据库

时间:2016-07-08 21:58:40

标签: ruby-on-rails ruby ruby-on-rails-4

我正在使用Rails构建一个事件站点,我不确定我的数据库是否正在捕获预订。我仍然处于开发模式,所以任何预订都是纯粹的'模拟'用于演示目的。我如何检查他们是否被记录(我很确定他们不是),如果他们不是 - 我该如何解决这个问题呢?

以下是相关代码 -

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"

我是否需要在预订表中添加booking_id?

1 个答案:

答案 0 :(得分:0)

我假设您使用migration创建了bookings架构。如果情况并非如此,请考虑使用它。

没有必要明确添加booking_id列,rails会添加它。关于确保保存记录,您可以使用begin/rescue clause

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

您还可以使用rails console查看数据库中最后一条Booking记录的内容。

$ rails c --sandbox
>> Booking.last

我希望有所帮助。