1

当我运行时:

IpPermission.blacklist.pluck(:ip)

我得到结果:

=> ["127.0.0.11012q", "50.36.46.48"] 

如果我手动更改 ip_permissions 表中的任何行,然后IpPermission.blacklist.pluck(:ip)再次运行。它显示更新的结果。它不应该从缓存而不是直接从数据库加载结果吗?

我的模型看起来像:

class IpPermission < ActiveRecord::Base
  validates_presence_of :ip, :note, :category
  validates_uniqueness_of :ip, :scope => [:category]
  validates :category, :inclusion => { :in => ['whitelist', 'blacklist'] }

  def self.whitelist
    Rails.cache.fetch('whitelist', :expires_in => 1.month) { self.where(:category => 'whitelist') }
  end

  def self.blacklist
    Rails.cache.fetch('blacklist', :expires_in => 1.month) { self.where(:category => 'blacklist') }
  end
end
4

1 回答 1

3

我认为这应该可以解决我们的问题:

改变这个

  def self.whitelist
    Rails.cache.fetch('whitelist', :expires_in => 1.month) { self.where(:category => 'whitelist') }
  end

  def self.blacklist
    Rails.cache.fetch('blacklist', :expires_in => 1.month) { self.where(:category => 'blacklist') }
  end

对此

  def self.whitelist
    Rails.cache.fetch('whitelist', :expires_in => 1.month) { self.where(:category => 'whitelist').all }
  end

  def self.blacklist
    Rails.cache.fetch('blacklist', :expires_in => 1.month) { self.where(:category => 'blacklist').all }
  end

where 不会进行实际查询,如果您放置.all则进行查询,因此您不存储数据,而只是存储查询

于 2012-11-09T09:58:23.440 回答