【问题标题】:Where does the site-wide footer logic belong in a Rails 3 app?站点范围的页脚逻辑在 Rails 3 应用程序中属于哪里?
【发布时间】:2011-02-26 17:36:14
【问题描述】:
我有一个站点范围的页脚,应该显示最近用户和帖子的列表。我想知道逻辑应该在哪里获取这些数据。我应该在 UsersController 中有一个“recent_users”方法,在 PostsController 中有一个“recent_posts”方法,还是应该有一个单独的 FooterController?
视图/帖子中的 _recent_users 部分视图/用户和 _recent_posts 部分视图如何让页脚部分呈现它们?
【问题讨论】:
标签:
ruby-on-rails
model-view-controller
ruby-on-rails-3
【解决方案1】:
所有“业务逻辑”都应该放在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 分钟过期一次(可能是最佳选择)。