开发者

How to use delegate method for more than two associations?

开发者 https://www.devze.com 2023-02-16 01:50 出处:网络
Let\'s say that I\'m retrieving the name of the sport by calling the following chain of 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.le开发者_Go百科ague.sport.name
end

But I want to use the delegate method!!!


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!


You could do the following:

class Pick
  def sport
    event.league.sport
  end

  delegate :name, :to => :sport
end

This would result in pick.name being equivalent to pick.event.league.sport.name.

0

精彩评论

暂无评论...
验证码 换一张
取 消