铁轨中最好的方法是什么?我想我可以进行一个查询以获取FOO的ID,然后在我必须渲染每个FOO时急切地加载的明确查找。是否有更好/更优雅/更惯用的方式来做到这一点?
您可以在控制器中使用fragment_exists?
就像以下:
if fragment_exists? "my_cache_key_#{id}"
# load your object without eager loading here
else
# eager load your objects here
end
<% cache("my_cache_key_#{@object.id}") do %>
...
...
...
<% end %>
应该为您做!
在@daviddb上为Rails 4的构建,具体来说,我发现有必要在控制器中为模板重新创建MD5哈希以进行比较的观点。
此外,也没有第一次找到对象,很难用最后修改的时间戳获取对象,因此我发现在没有
skip_digest
的情况下进行初始查询很有帮助
.includes(:object1, :object2)
views/customers/show.html.slim
- cache['customers/show', @customer], skip_digest: true do
h1
= @customer.account.name
= render 'account_summary', account: @customer.account
= render 'account_details', transactions: @customer.account.transactions
...
controllers/customers_controller.rb
注:通过设置
def show
customer = Customer.find(params[:id])
if fragment_exist?(['customers/show', customer])
@customer = customer
else
@customer = Customer.includes(account: :transactions).find(params[:id])
end
end
在更改此视图时,您需要在部署时清除缓存以及其依赖的任何部分以确保正确渲染新布局。
我在使用lambda的缓存中做了类似的事情。 在下面,您可以得到一个主意。问题所解决的问题 - 获得最受欢迎的用户是一个重型操作,需要> 5秒。但是使用lambda,您可以缓存用户列表。
skip_digest: true
您可以将俄罗斯娃娃缓存用于此类问题,例如,我们有评论和作者的帖子,在主页中,您可以使用
controller:
def index
@users = -> { User.by_rating }
end
view:
= cache "rating-list", expires_in: 1.day do
- @users.call.each do |user|
= render user
视图
# HomeController
def index
@posts = Post.includes(:author, :comments).limit(10)
end