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

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?

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 https://www.railsagency.com/blog/2016/10/14/simple-polymorphic-selects-with-global-ids/

Join the discussion

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

Join 38,558+ 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.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.