I have the following method to check if a user has admin access.
def has_admin_access?(user)
user.present? && gym_users.where(:role_id => [3, 4]).where(['user_id = ? AND date_ended IS NULL', user.id]).any?
end
The problem comes when I want 开发者_运维问答to call this multiple times on a page. How can I do this so that I set a private value and only make the database call the first time?
You can just store the result in a hash, and if you look up the same user again return the result from the hash. Like this:
def has_admin_access?(user)
@admin_hash ||= {}
if (!@admin_hash.include?(user))
@admin_hash[user] = user.present? && gym_users.where(:role_id => [3, 4]).where(['user_id = ? AND date_ended IS NULL', user.id]).any?
end
@admin_hash[user]
end
Try:
extend ActiveSupport::Memoizable
memoize :has_admin_access?
more information
精彩评论