Ruby on rails Rails 4:在嵌套循环中按时间顺序对项目进行排序

Ruby on rails Rails 4:在嵌套循环中按时间顺序对项目进行排序,ruby-on-rails,loops,sorting,ruby-on-rails-4,Ruby On Rails,Loops,Sorting,Ruby On Rails 4,在我的Rails 4应用程序中,我有以下型号: class User < ActiveRecord::Base has_many :administrations has_many :calendars, through: :administrations end class Calendar < ActiveRecord::Base has_many :administrations has_many :users, through: :administratio

在我的Rails 4应用程序中,我有以下型号:

class User < ActiveRecord::Base
  has_many :administrations
  has_many :calendars, through: :administrations
end

class Calendar < ActiveRecord::Base
  has_many :administrations
  has_many :users, through: :administrations
  has_many :posts
  has_many :comments, through: :posts
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Post < ActiveRecord::Base
  belongs_to :calendar
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  delegate :first_name, to: :user, prefix: true
end
在我的
Calendar#Index
视图中,我编写了以下代码:

<table id="my_todo_table">

  <% @calendars.each do |calendar| %>

    <% calendar.comments.each do |comment| %>

      <tr>

        <td><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span> <%= link_to calendar.name, calendar_path(calendar.id) %></td>
        <td><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> <%= comment.post.subject %> </td>
        <td><span class="glyphicon glyphicon-user" aria-hidden="true"></span> <%= comment.user.first_name %></td>
        <td><span class="glyphicon glyphicon-comment" aria-hidden="true"></span> <%= comment.body %></td>

      </tr>

    <% end %>

  <% end %>

</table>

除了一个小细节外,这个方法工作得很好:目前,评论是按日历排序的,然后按帖子排序(考虑到上面的代码,这是有道理的)

相反,我希望将它们按时间顺序排序,即最新的第一个,无论它属于哪个日历或帖子


有什么方法可以做到这一点吗?

您可以通过在日期时间创建的
进行订购,如下所示:

def index
  @user = current_user
  @calendars = Comment.where("user_id like ?", @user.id).order("created_at DESC")
end

您可能可以对注释执行一个新的ActiveRecord查询,因为您是通过日历获取注释的,我会这样做

@comments = Comment.joins(post: :calendar).where(calendars: {id: @calendars.pluck(:id)}).distinct.order(created_at: :desc)

这将找到属于日历的所有评论,并根据创建的时间戳对评论进行排序

谢谢您的回答。这是我的评论吗?还是我的日历?这将为您订购日历。这就是你要找的吗?您需要订购一些东西,无论是基于日历、帖子还是评论。不,我不想订购日历。我想订购这些评论。我理解你在等号右侧写的内容,但我觉得我们不应该将
评论
存储在
@日历
中。请使用您的评论并更正。变量名称的变化实例
@comments = Comment.joins(post: :calendar).where(calendars: {id: @calendars.pluck(:id)}).distinct.order(created_at: :desc)