简体   繁体   中英

how to prevent stacked ordering when I do Z=X+Y? X is always on top

Here's what I mean

This is my controller

class StaticPagesController < ApplicationController

  def home
    if signed_in?
      @post_items = current_user.posts
      @activities = PublicActivity::Activity.order("created_at desc")
      @items = @post_items + @activities
      @items.sort_by{|item| item.class == PublicActivity::Activity ? item.created_at : item.created_at}
      @items = @items.paginate(:page => 1, :per_page => 20)
    else
    redirect_to root_path  
    end
  end

As you can see in the above, this line @items = @post_items + @activities causes stacked ordering. All of the post_items are ordered first THAN the activities are ordered below it.

I am trying to combine BOTH into one ordering using "created_at".

How can I prevent this stacked ordering and make it order as one? Thanks

sort_by isn't doing what you think it's doing. It's returning a new sorted array. If you want to modify the array in-place, you have to use sort_by! :

@items.sort_by!(&:created_at)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM