Rails booking feature with Payment Gateway

63 Views Asked by At

novice Rails Back-end developer here. Trying to integrate a payment gateway for the first time. Hopefully I can manage to explain everything fine.

I'm building a booking marketplace platform using the payment gateway Mangopay (unnecessary to know this tech for my request)

So, from how I imagined the booking process, I have these 2 models :

Bookings

# Schema
create_table "bookings", force: :cascade do |t|
  t.bigint "booking_transaction_id", null: false
  ...
end

# Model
class Booking < ApplicationRecord
  belongs_to :user
  has_one :booking_transaction
  ...
end

Booking_transactions (responsible for all the logic between a booking and the payment gateway)

# Schema
create_table "booking_transactions", force: :cascade do |t|
  t.bigint "booking_id", null: false
  ...
end

# Model
class BookingTransaction < ApplicationRecord
  belongs_to :booking
  ...
end

I then have a controller where I want to create a booking. But a booking needs a booking_transaction right ? I started writing something like such in my controller :

def create
  booking = current_user.bookings.create!(

  )
end

But of course, I get a NotNullViolation because creating a booking require to have a booking_transaction_id. So I'm not sure what the process should look like.

Thanks in advance for any given help.

1

There are 1 best solutions below

0
user12178999 On

Turns out I shouldn't have the 2 models requiring each other.

I removed the booking_transaction reference (ie booking_transaction_id) from the booking model.

And can now create a booking like this :

def create
  transaction = BookingTransaction.new

  booking = current_user.bookings.create!(
    transaction: transaction
    ...
  )
end

This will then create a booking_transaction and attach it on the newly created booking instance thanks to the Rails Way.