开发者

Rails: Set a private value so it only calls the database once

开发者 https://www.devze.com 2023-03-19 16:10 出处:网络
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 NUL

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

0

精彩评论

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