【问题标题】:render the newest of two partials in the same stream在同一流中渲染两个部分中的最新部分
【发布时间】:2012-08-17 13:50:31
【问题描述】:

我有两种不同类型的对话,开始和加入。我想将它们一起呈现在同一个流中,从顶部最新到底部最旧。也就是说,我希望它们混合在一起,以便最新的对话位于顶部,无论它是由用户发起还是由用户加入(即由另一个用户发起)。

来自我的控制器:

def conversations
  @user = current_user
  @joined_conversations = @user.received_meeting_requests.paginate(page: params[:page], :conditions => ['state = ?', 'replied'])
    @started_conversations = @user.sent_meeting_requests.paginate(page: params[:page], :conditions => ['state = ?', 'replied'])
end

在我看来,我是这样渲染的:

<ol class="meetings">
  <%= render @started_conversations %>
  <%= render @joined_conversations %>
</ol>
  <%= will_paginate @started_conversations %>
  <%= will_paginate @joined_conversations %>
<% end %>

因此,即使是最早开始的对话也会在最新加入的对话之上。如何渲染这两个对象以使它们混合在一起,即最新开始或加入的对话将始终位于顶部?谢谢!

【问题讨论】:

    标签: ruby-on-rails rendering


    【解决方案1】:

    嗯,实际上有几种方法可以实现,但您需要的是在一个集合中进行两种对话。

    现在,您可以将现有的两个集合放在一起(使用数组联合运算符'|'),然后再使用它们:

    def conversations
      @user = current_user
      @joined_conversations = @user.received_meeting_requests.paginate(page: params[:page], :conditions => ['state = ?', 'replied'])
      @started_conversations = @user.sent_meeting_requests.paginate(page: params[:page], :conditions => ['state = ?', 'replied'])
      @conversations = (@joined_conversations | @started_conversations).sort_by{|c| c.created_at}
    end
    

    但是,由于这种过滤和排序是数据库的真正用途,我认为您最好在一个查询中收集所有相关的对话。我想告诉你那个查询是什么,但是如果不知道你的模型/表是什么,它们是如何关联的,用户加入或开始对话意味着什么,以及对于这与您使用的 Rails 版本和数据库无关,因为它在 Rails 3.x 和 2.x 中看起来会有很大不同。

    在任何一种情况下,您最终都会得到一个名为 @conversations 的集合,并且应该能够简单地呈现它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-30
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多