Delegation within the Ruby on Rails framework is a fantastic way of keeping Active Relation code clean and readable. When you use the delegate keyword in Ruby on Rails you are giving the responsibility of retrieving a certain piece of data to another type of object within a relation. A good example is of a data entry application. You have certain pieces of data entered by users, and for maintenance purposes we must track who has entered which data points. With Ruby on Rails this is fairly simple when we use relations. Lets call our model ExampleSubject and it will hold data about our lab experiment.
As you can see plainly each example subject belongs to a user that has entered them into the system. Now when we go to our dashboard to look at all of the experiments in the system we’ll see code that looks like this.
While this example is slightly contrived you can plainly see the email field being accessed through the user relation. While this specific example it isn’t such a pain to deal with accessing data through relations like the erb template above can lead to some incredibly messy code. That’s where delegates come in! We can hold the email address data with our ExampleSubject model by giving the responsibility of getting that data to us to the User model. Check out the Gist below.
As you can see the delegate key word has now been placed in our ExampleSubject model. It’s indicating that the email attribute on the Example subject model will be given to us by the User model. Now lets check out our new and improved erb code.
Nice and tidy! we now use the ExampleSubject model directly to retrieve the email data from the user that entered the data’s User model in the database. Again this example is relatively simplistic so if you have any questions or comments feel free to leave something in the comments and I’ll get back to you ASAP!