Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use delegate method for more than two associations?

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!!!

like image 826
keruilin Avatar asked Mar 09 '11 23:03

keruilin


People also ask

How does delegate work in Ruby?

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.

How does delegate work in Rails?

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.

What are delegate methods?

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.

What is Simpledelegator?

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.


1 Answers

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!

like image 97
andrea Avatar answered Sep 20 '22 01:09

andrea