我混合了两个数组,并希望根据它们的created_at属性对它们进行排序:
@current_user_statuses = current_user.statuses
@friends_statuses = current_user.friends.collect { |f| f.statuses }
@statuses = @current_user_statuses + @friends_statuses
@statuses.flatten!.sort!{ |a,b| b.created_at <=> a.created_at }@current_user_statuses和@friends_statuses都能正确排序,但组合起来却不能正确排序,@friends_statuses始终显示在顶部,按其created_at属性排序,@current_user_statuses显示在底部,按其created_at属性排序。
这是视图:
<% @statuses.each do |d| %>
<%= d.content %>
<% end %>发布于 2011-07-03 00:01:45
尝试:
(current_user.statuses + current_user.friends.collect(&:statuses)) \
.flatten.compact.sort_by(&:created_at)发布于 2011-07-02 22:59:36
你不能像那样用菊花链链接flatten!方法。如果未对数组进行任何更改,则flatten!返回nil。当你排序为nil时,什么都不会发生。
您需要将它们分开:
@statuses.flatten!
@statuses.sort! { ... }发布于 2011-07-03 01:51:32
我是这样做的:
设置类:
class User
class Status
attr_reader :statuses, :created_at
def initialize(stats)
@statuses = stats
@created_at = Time.now
end
end
attr_reader :statuses, :friends
def initialize(stats=[], friends=[])
@statuses = Status.new(stats)
@friends = friends
end
end定义一些实例,只是为了好玩而留出一些时间间隔:
friend2 = User.new(%w[yellow 2])
sleep 1
friend1 = User.new(%w[orange 1])
sleep 2
current_user = User.new(%w[green 1], [friend1, friend2])下面是我如何以不同的方式来做;以created_at顺序获取状态:
statuses = [
current_user.statuses,
current_user.friends.collect(&:statuses)
].flatten.sort_by(&:created_at)看起来是这样的:
require 'pp'
pp statuses
# >> [#<User::Status:0x0000010086bd60
# >> @created_at=2011-07-02 10:49:49 -0700,
# >> @statuses=["yellow", "2"]>,
# >> #<User::Status:0x0000010086bc48
# >> @created_at=2011-07-02 10:49:50 -0700,
# >> @statuses=["orange", "1"]>,
# >> #<User::Status:0x0000010086bb30
# >> @created_at=2011-07-02 10:49:52 -0700,
# >> @statuses=["green", "1"]>]我只是构建了一个临时的包含数组来保存current_user的状态,以及所有好友的状态,然后将其扁平化。
(&:statuses)和(&:created_at)参数是实例的statuses方法或实例的created_at方法的Rails简写形式。
https://stackoverflow.com/questions/6557585
复制相似问题