所有「業務邏輯」應該放在Model
,而不是的控制器中。最近用戶和帖子的查詢應該在User
和Post
模型中。然後,如果您有站點範圍的視圖元素,請將其移至部分並將該部分添加到application.html.erb
中。
# User.rb
model User
def recent
# logic and query here
end
end
# Post.rb
(see above)
# application_controller.rb
before_filter :get_recent_posts
before_filter :get_recent_users
...
private
def get_recent_posts
@recent_posts = Post.recent
end
def get_recent_users
@recent_users = User.recent
end
# application.html.erb
...
<%= yield %>
...
<%= render :partial => 'layouts/footer', :locals => { :recent_users => @recent_users, :recent_posts => @recent_posts } %>
# layouts/_footer.html.erb
<% recent_users.each do |user| %>
<%= link_to user.name, user %>
<% end %>
# same for posts
一些重要的事情需要注意:
不訪問在部分實例變量(@foo)...它傳遞到當地人的哈希和訪問它作爲一個變量代替。這只是一般不好的做法
你也可以使用一個模塊
直視緩存,因爲你可能不希望兩次擊中你的數據庫中每個頁面加載。您可以在頁腳上使用片段緩存,並每15分鐘過期一次(可能是最好的選擇)。