This article will discuss a very useful method in Ruby on Rails - ActiveRecord, i.e. delegate. According to the documentation, delegate:
provides a delegate class method to easily expose contained objects’ public methods as your own.
Here’s an example: Assume you have a user model that has one object of the address model. The address model contains address1, address2, city, state, and zip as attributes. Create these models first.
1 2 3 rails g model User name rails g model Address address1 address2 city state zip user:belongs_to rails db:migrate
In the user.rb, put this:
1 has_one :address
In address.rb, put the following method:
1 2 3 def formatted_address address1.to_s + ' ' + address2.to_s + ' ' + city.to_s + ',' + ' ' + state.to_s + ' ' + zip.to_s end
Now create one record each for the specified models.
1 2 3 4 rails console User.create(name: "John") user = User.first user.create_address(address1: "797 Fulton Road", address2: nil, city: "Clinton", state: "MD", zip: "20735")
If you want a formatted address against this user, you might do something like this:
However, this doesn’t look good and requires more writing than necessary. Here’s where delegate comes in. Go ahead and try it to see the magic.
In user.rb, add this line:
1 delegate :formatted_address, to: :address
Now you can access the formatted address directly from the user object.
There you have it! Happy formatting!