Ask A Question

Notifications

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
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?

Reply

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.

Reply

And this would make for a fantastic screencast... ๐Ÿ˜Ž

Reply

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/

Reply

Did this ever get made into a screencast?

Reply
Reply

๐Ÿ‘

Reply

Okay, thats what actually I was looking for though

Reply
Join the discussion
Create an account Log in

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

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

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