Let's say that I'm retrieving the name of the sport by calling the following chain of associations:
pick.event.league.sport.name
How can I use the delegate method so that I can just call *pick.event_league_sport_name* like so? Obviously, I can create a method in the pick model:
def event_league_sport_name
return self.event.league.sport.name
end
But I want to use the delegate method!!!
Delegation can be done explicitly, by passing the sending object to the receiving object, which can be done in any object-oriented language; or implicitly, by the member lookup rules of the language, which requires language support for the feature.
On the Profile side we use the delegate method to pass any class methods to the User model that we want access from our User model inside our Profile model. The delegate method allows you to optionally pass allow_nil and a prefix as well. Ultimately this allows us to query for data in custom ways.
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
A concrete implementation of Delegator , this class provides the means to delegate all supported method calls to the object passed into the constructor and even to change the object being delegated to at a later time with #__setobj__. class User def born_on Date.
I dont suggest this , but if you want ...
delegate :name , :to => "event.league.sport" ,:prefix=>"event_league_sport"
also without prefix.
be sure to handle nil associations ...
have a nice day!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With