How to use delegate method for more than two associations?
Asked Answered
L

2

7

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

Logotype answered 9/3, 2011 at 23:31 Comment(0)
D
5

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.

Deerstalker answered 10/3, 2011 at 0:34 Comment(0)
N
14

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!

Numbers answered 10/3, 2011 at 0:35 Comment(0)
D
5

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.

Deerstalker answered 10/3, 2011 at 0:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.