optimization - Saving result of has_one association to avoid fetching DB in Rails? -


i have has_one association between user model , player model. see myself doing current_user.player many times in controllers , views, , feel hitting db way every time that. nice have current_player method.

how , define method can access current_player both controllers , views?

it's (properly) going reload @ least once each time hit page, can prevent following loads memoizing result:

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

as alternative, possibly include player model in default scope, loads whenever user model loaded:

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

unfortunately, whenever i've tried tend find didn't want auto-loading other table every time, , switch previous method loads 2nd table on first use. memoizing object ivar vastly more flexible.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -