How do I create an input field for a polymorphic association?
For the sake of this question, lets assume I run a hotel and I want to make a system that manages the bookings of my hotel rooms.
While most of the time I book
Guests in my hotel rooms,
Employees have the ability to book a room too.
The basic relationships begin to look like this.
class Guest has_many :bookings, as: :bookable end class Employee has_many :bookings, as: :bookable end class Booking belongs_to :bookable, polymorphic: true belongs_to :room end class Room has_many :bookings end
I want to create a form to create bookings. How would you go about creating a form element that can select a guest or an employee?
One trick I like is using signed GlobalIDs. This way you can reference any model. Your form could list all the guests and employees and submit their SGID over to the booking to be transformed to the proper record.
They must be signed global IDs to prevent tampering though.
Haha oh yes please for a screen cast...
I found this tutorial that seems to be useful https://www.railsagency.com/blog/2016/10/14/simple-polymorphic-selects-with-global-ids/