我应该在哪个控制器中放置在整个应用程序中持久存在的元素?

时间:2012-03-14 09:21:59

标签: ruby-on-rails

@posts之后的所有内容都应该在整个应用程序中持续存在(就像您在Facebook上找到的左侧边栏一样)。

  def index
    @title = "Posts"
    default_order = "content_changed_at DESC"
    params[:order_by] ||= default_order 
    @posts = current_user.subscribed_posts.paginate(:page => params[:page],
                                                    :per_page => 5,
                                                    :order => params[:order_by])
    @subscribed_tags = current_user.subscribed_tags
    @recent_posts = current_user.posts.limit(5).order("created_at DESC")
    @tags= Tag.limit(20).order("ID asc")
    @user = current_user
  end

视图/布局/ _sidebar.html.erb:

    <div class="user-profile">
      <% avatar = image_tag(current_user.avatar.url(:thumb), :class => "authenticated-avatar") %>
      <%= link_to avatar, "/users/#{current_user.id}" %>
      <%= link_to "#{current_user.username}", "/users/#{current_user.id}", :class => "authenticated-username" %>
    </div>

    <%= form_for(@user, :remote => true) do |f| %>
      <div class="field">
        <%= f.label :subscribed_tag_names %><br />  
        <%= f.autocomplete_field :subscribed_tag_names, autocomplete_tag_name_posts_path, :"data-delimiter" => ' ', :class => "autocomplete_field" %>
      </div>
      <div class="actions">
        <%= f.submit :class => "user_subscribed_tag_names_submit" %>
      </div>
    <% end %>

    <div class="user-subscribed_tags">
      <% @subscribed_tags.each do |subscribed_tag| %>
        <%= link_to "#{subscribed_tag.name}(#{subscribed_tag.posts.count})", unsubscribe_tags_path(:unsubscribed_tag_name => subscribed_tag.name) %>
      <% end %>
    </div>

    <div class="user-recent-posts">
      <h4>Recent Posts</h4>
      <ul>
        <% @recent_posts.each do |recent_post| %>
          <li><%= link_to recent_post.title, recent_post %></li>
        <% end %>
      </ul>
    </div>

    <div class="top-tags">
      <% @tags.each do |tag| %>
        <span class="tag-name"><%= tag.name %></span>
        <span class="tag-count"><%= tag.posts.count %></span>
      <% end %>
    </div>
  <% end %>

如果我希望它们在整个应用程序中持久存在,我应该将代码放在控制器中? (如果可能的话,我想看一些示例代码。)

1 个答案:

答案 0 :(得分:3)

如果它在整个应用程序中持续存在,即对于所有控制器的每个操作,您可以将它放在应用程序控制器中的before_filter中。

before_filter添加到应用程序控制器:

before_filter :find_recent_posts_and_tags

并定义它(作为私人):

private
def find_recent_posts_and_tags
  # define your instance variables
end

有关过滤器herehere的更多信息。