强制重新加载has_one / belongs_to关联

时间:2015-03-26 13:10:19

标签: ruby-on-rails ruby ruby-on-rails-4

我有两个型号

class User < ActiveRecord::Base
.
.
    has_one :profile, :dependent => :destroy
.
.
end

class UserMilaapDetail < ActiveRecord::Base
.
.
    belongs_to :user
.
.
end

因此,当我自动执行user.profile而不执行Profile时,我需要从数据库中获取user.profile(true)的副本,而不是从缓存中获取。我可以在指定关联时实现吗?如果没有替代方案?

1 个答案:

答案 0 :(得分:1)

Per https://coderwall.com/p/zifrrw/clear-cache-of-a-ruby-on-rails-association看起来您可以选择在关联上调用#reset来清除它以进行下一次调用,但听起来并非如此。

我不知道有一种简单的方法可以让rails本身为一个关联永久禁用缓存。

我认为最好的方法是创建另一个可以调用此方法的方法。

def uncached_profile
    profile(true)
end

如果要保留对象的outfacing配置文件方法,可以使用alias_method_chain重新定义#profile:

def profile_with_no_caching(reload = true)
   profile_without_no_caching(reload)
end
alias_method_chain :profile, :no_caching