0

I have a has_one association between User model and Player model. I see myself doing current_user.player so many times in controllers and views, and I feel like I am hitting the DB way too much every time I do that. Also it would be nice to have a current_player method.

How and where would I define a method like that so I can access current_player from both the controllers and the views?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

0

It's (properly) going to reload at least once each time you hit the page, but you can help prevent following loads by memoizing the result:

class User
  has_one :player
  def current_player
    @current_player ||= player
  end
end

As an alternative, you could possibly include the player model in the default scope, so it loads whenever the User model is loaded:

class User
  has_one :player
  default_scope includes(:player)
end

Unfortunately, whenever I've tried that I tend to quickly find I actually didn't want it auto-loading the other table every time, and switch back to the previous method which only loads from the 2nd table on first use. Simply memoizing the object into an ivar is vastly more flexible.

pdkl95
  • 187
  • 1
  • 10
  • Thanks for the answer. That would make me fetch the current player by doing current_user.current_player. How would I just access current_player from both the controller and the views? – Hommer Smith Jul 03 '12 at 18:34