0

我在 static_pagehome.html.erb中有一个提要,我正在尝试组合两个渲染

这就是我的意思:

首先这是我的控制器

class StaticPagesController < ApplicationController
  def home
    if signed_in?
      @micropost = current_user.microposts.build
      @activities = PublicActivity::Activity.order("created_at desc").paginate(page: params[:page]) 
      @feed_items = current_user.feed.paginate(page: params[:page]) 
    else
    redirect_to root_path  
    end
  end

这就是我在视图中使用的

<%= render partial: 'shared/feed_item', collection: @feed_items %>
<%= will_paginate @feed_items %>

这是在我想加入的视图中呈现的视图shared/feed_item,以便它们都按降序显示在同一个列表中@feed_items@activities@feed_items

<li id="<%= feed_item.id %>">
<br>
  <%= link_to gravatar_for(feed_item.user), feed_item.user %>
  <%= link_to feed_item.user.name, feed_item.user %>
  <span class="textname">shared this</span><span class="timestamp"> <%= time_ago_in_words(feed_item.created_at) %> ago.
  </span>  
  </li>

我可以使用某种形式的 if-else 将此视图集成@activities到上面的代码中,以使它们成为一个列表的一部分吗?

<li>

  <% if activity.trackable_type == "Micropost" %>
    <span class="user"><%= link_to activity.owner.name, activity.owner if activity.owner %></span><span class="textname"> posted this</span><span class="timestamp"> <%= time_ago_in_words(activity.created_at) %> ago.
  </span>
  <% else %>
   <span class="user"><%= link_to activity.owner.name, activity.owner if activity.owner %></span><span class="textname"> made a comment</span><span class="timestamp"> <%= time_ago_in_words(activity.created_at) %> ago.
  </span>
  <% end %>
</li>

我通过加入 _activity.html.erb 和 _feed_items.html.erb 创建的完整 _item.html.erb

<li>
<% if item.class == PublicActivity::Activity %>
   <% if activity.trackable_type == "Post" %>
     <%= link_to activity.owner.name, activity.owner if activity.owner %><span class="textname"> posted </span><span class="timestamp"> <%= time_ago_in_words(activity.created_at) %> ago.
  </span>
  <% else %>
   <%= link_to activity.owner.name, activity.owner if activity.owner %><span class="textname"> made a comment</span><span class="timestamp"> <%= time_ago_in_words(activity.created_at) %> ago.
  </span>
  <% end %>
<% else %>

<br>
   <span class="user">
    <%= link_to feed_item.user.name, feed_item.user %>
      </span>
      <span class="textname">shared this</span><span class="timestamp"> <%= time_ago_in_words(feed_item.created_at) %> ago.
  </span>

  </li>
  <% end %>
4

1 回答 1

0

您可以创建一个包含活动和提要的数组。

在您的控制器中:

...
@items = @activities + @feed_items
@items.sort_by{|item| item.class == Activity ? item.an_activity_field : item.a_feed_item_field}
...

然后在你看来:

<%= render partial: 'shared/partial_name', collection: @items %>
<%= will_paginate @items %>

在你的部分:

<% if item.class == Activity %>
  # activity display stuff
<% else %>
  # feed display stuff
<% end %>

如果你遵循这个,你将不得不在你的分页中加入更多的逻辑。

于 2013-04-30T04:14:49.437 回答