Search code examples
ruby-on-railsnested-attributeshas-many-through

has_many with multiple table


I have a MovieSession has many ticket

class MovieSession < ActiveRecord::Base
has_many :tickets
end

A ticket belongs_to a room and has many bookings

class Ticket < ActiveRecord::Base
has_many :bookings
belongs_to :room
end

Booking like a join table between Seat and Ticket

class Booking < ActiveRecord::Base
belongs_to :ticket
belongs_to :seat
end

In rails is it possible if I get all booked seat. Like below?

class MovieSession < ActiveRecord::Base
has_many :seats, through :ticket and booking 
end

Solution

  • If you want to get all the seats for a movie, you want to go to the seat model and add a scope that joins the appropriate tables. Something like:

    class Seat < ActiveRecord::Base
      belongs_to :booking
    
      scope :by_movie, -> (_movie) { joins(:booking => {:ticket => :movie}).where(movie: _movie) }