How to use the delegate method for more than two associations?

Let's say that I get the name of the sport, causing 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 * in the same way? Obviously, I can create a method in the selection model:

 def event_league_sport_name return self.event.league.sport.name end 

But I want to use the delegate method .

+4
source share
2 answers

You can do the following:

 class Pick def sport event.league.sport end delegate :name, :to => :sport end 

This will cause pick.name be equivalent to pick.event.league.sport.name .

+3
source

I do not suggest this, but if you want ...

 delegate :name , :to => "event.league.sport" ,:prefix=>"event_league_sport" 

also without a prefix.

be sure to handle nil associations ...

we have a good day!

+7
source

Source: https://habr.com/ru/post/1343086/


All Articles