我目前正在开发一个使用 Rails 5 的项目。我想提高性能,所以我决定使用低级缓存,如下所示:
class User < ApplicationRecord
has_one :profile
def cached_profile
Rails.cache.fetch(['Users', id, 'profile', updated_at.to_i]) do
profile
end
end
end
class Profile < ApplicationRecord
belongs_to :user, touch: true
end
分别工作得很好。但现在我想让两个缓存协作。我想要的是,一旦从缓存存储(这里是redis)检索关联对象,就不需要从数据库检索它。
irb> u = User.take
irb> u.cached_profile # fetch from the redis. Can I set the association caching in `cached_profile`?
irb> u.profile # fetch from the database
Profile Load (1.4ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
irb> u.profile # fetch from the association caching
u.profile
不应该从数据库中获取,因为它已经从redis中检索,如何实现这一点?
更新1:
我发现有一个实例变量@association_cache
在实例中ActiveRecord::Base
,它存储缓存的关联并确定是否应从数据库检索关联。
我想我可以做类似的事情user.instance_variable_get(:@association_cache)['profile'] = cached_profile
使其发挥作用。但其中的价值@association_cache
是一个实例ActiveRecord::Associations::HasOneAssociation
我不知道如何构建user
目前。