All threads / How do I properly use the delegate method?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I properly use the delegate method?

Taylor Cooney asked in Rails

I'm curious how this can be correctly applied to a booking application. If you have a Reservation and Customer model, does it make sense to store information such as the first name, last name, and email address on the Reservation model, as well as the Customer model, or is this where delegate could be used?

I'm not sure if this is an obscure way to use it and should be storing this information on both models.

Yep, that could be a good use case. I use it frequently for things like that. It's not really any different than saying reservation.customer&.name though with the new Ruby safe operator. It's basically doing that for you in the delegate method, but delegate will let you say reservation.name instead of having to know the customer lives in between.

Thanks for confirming that Chris, I loved the latest episode on Google Maps.

I think delegate is a great way to limit the responsibility of keeping the data in-sync, if Reservation, Customer and User all had individual address attributes and top level attributes, like name, email, phone number, that could be a PITA to keep up-to-date.

Exactly. And if you need to rename it or make it more complex, delegate can still let you call reservation.name even though it might delegate through a few objects if you had to add like approvals or some other model in the mix that made things more complex.

Join the discussion

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

Join 48,387+ 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

    © 2021 GoRails, LLC. All rights reserved.