All threads / How do I create an input field for a polymorphic association?
Ask A Question


You’re not receiving notifications from this thread.

How do I create an input field for a polymorphic association?

Peter Marcano asked in Rails

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

class Employee
  has_many :bookings, as: :bookable

class Booking
  belongs_to :bookable, polymorphic: true
  belongs_to :room

class Room
  has_many :bookings

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.

And this would make for a fantastic screencast... 😎

Haha oh yes please for a screen cast...

I found this tutorial that seems to be useful

Did this ever get made into a screencast?

Okay, thats what actually I was looking for though

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 68,326+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.