簡體   English   中英

如何在Rails 4中緩存個性化片段?

[英]How do I cache a personalised fragment in Rails 4?

我的應用程序(Rails 4)允許用戶對帖子進行投票。 是否可以緩存帖子,但個性化投票緩存,以便顯示一個針對current_user的個性化? 例如,用戶是否投票。

我寧願不改變html結構來實現這一點。

# posts/_post.html.slim
- cache post do
  h1 = post.title
  = post.text
  = render 'votes/form', post: post

# votes/_form.html.slim
- if signed_in? && current_user.voted?(post)
  = form_for current_user.votes.find_by(post: post), method: :delete do |f|
    = f.submit
- else
  = form_for Vote.new do |f|
    = f.submit

你有兩個選擇:

選項1:不要緩存投票

這是最簡單的解決方案,也是我個人推薦的解決方案。 您只是不緩存動態用戶相關部分,因此您有這樣的事情:

# posts/_post.html.slim
- cache post do
  h1 = post.title
  = post.text
= render 'votes/form', post: post # not cached

選項2:使用javascript

這個解決方案更復雜,但實際上是basecamp如何做到這一點(但主要是用更簡單的例子)。 您在頁面上呈現了兩個部分,但使用javascript刪除其中一個部分。 以下是使用jQuery和CoffeeScript的示例:

# posts/_post.html.slim
- cache post do
  h1 = post.title
  = post.text
  = render 'votes/form', post: post

# votes/_form.html.slim
div#votes{"data-id" => post.id}
  .not_voted
    = form_for current_user.votes.find_by(post: post), method: :delete do |f|
      = f.submit
  .voted
    = form_for Vote.new do |f|
      = f.submit

# css
.not_voted {
  display:none;
}

# javascript (coffeescript)
jQuery ->
  if $('#votes').length
    $.getScript('/posts/current/' + $('#votes').data('id'))

# posts_controller.b
def current
  @post = Post.find(params[:id])
end

# users/current.js.erb
<% signed_in? && current_user.voted?(@post) %>
  $('.voted').hide();
  $('.not_voted').show();
<% end %>

然而,我會適當改變voted? 接受id的方法,因此您不需要進行新的查詢。 您可以在此railscast中了解有關此方法的更多信息: http: //railscasts.com/episodes/169-dynamic-page-caching-revised?view=asciicast

嘗試以下操作,這將為每個帖子創建兩個不同的片段,用於投票和未投票。 它將根據其狀態進行閱讀。

# posts/_post.html.slim
- cache [post, current_user.votes.find_by(post: post)]do
  h1 = post.title
  = post.text
  = render 'votes/form', post: post

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM