Rails: extra field in many to many

There's something wrong I did with my schema, but I don't understand what exactly and how to make it work like I want to:

  • A flight has many seats
  • A seat can be used in many flights
  • For every combination of flight and seat there's a booking
  • One booking can have many flight/seat combinations
  • I should be able to see flight.seats.first.booking

Here're parts of schema.rb:

create_table "seats", force: :cascade do |t|
  t.integer "airplane_id"
  t.string "row"
  t.integer "column"
end

create_table "flights", force: :cascade do |t|
  t.integer "route_id"
  t.integer "airplane_id"
end

create_table "flights_seats", id: false, force: :cascade do |t|
  t.integer "flight_id"
  t.integer "seat_id"
  t.integer "booking_id"
end

The booking class has nothing interesting

1 answer

  • answered 2018-01-12 03:32 John Bachir

    I think maybe the solution is to make Booking a bit more interesting :)

    flights_seats with three object ids is a bit of a red flag.

    How about this:

    Booking
      belongs_to :flight # flight_id column
      has_many :tickets
    
    Ticket
      belongs_to :booking # booking_id column
      belongs_to :seat # seat_id column
    
    # remove flights_seats
    

    I don't know all your needs but I think that will get you in the right direction.