开发者

Where does the site-wide footer logic belong in a Rails 3 app?

开发者 https://www.devze.com 2023-02-13 10:02 出处:网络
I have a site-wide footer that should display a list of recent Users and Posts. I\'m wondering where the logic should to gets this data. Should I have a \"recent_users\" method in the UsersController

I have a site-wide footer that should display a list of recent Users and Posts. I'm wondering where the logic should to gets this data. Should I have a "recent_users" method in the UsersController 开发者_如何学Goand a "recent_posts" method in the PostsController, or should I have a separate FooterController?

How about a _recent_users partial views/users and a _recent_posts partial in views/posts and have the footer partial render both of them?


All "business logic" should be put in the Model, not the controller. The query for recent Users and Posts should be in the User and Post model. Then, if you have a site-wide view element, move it into a partial and add that partial into the 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

A few important things to note:

  1. don't access the instance variables (the @foo) in the partial... pass it into the locals hash and access it as a variable instead. It's just generally bad practice

  2. you could also use a module

  3. look into caching because you probably don't want to hit your database TWICE on every page load. You could use fragment caching on the footer and expire it every 15 minutes (probably the best option).

0

精彩评论

暂无评论...
验证码 换一张
取 消