如何按created_at属性对集合进行排序

时间:2010-12-06 19:39:24

标签: ruby-on-rails ruby

我正在使用Ruby on Rails 2.3.8,我有一个由其他两个集合构建的集合,如下所示:

@coll1 = Model1.all
@coll2 = Model2.all

@coll = @coll1 << @coll2

现在,我想按照created_at属性按后代顺序对该集合进行排序。所以,我做了以下几点:

@sorted_coll = @coll.sort {|a,b| b.created_at <=> a.created_at}

我有以下例外:

undefined method `created_at' for #<Array:0x5c1d440>

eventhought它存在于那些模型中。

请帮帮我吗?

4 个答案:

答案 0 :(得分:23)

您正在将另一个数组作为另一个元素推入@coll1数组,您有两个选择:

展平生成的数组:

@coll.flatten!

或者最好只使用+方法:

@coll = @coll1 + @coll2

对于排序,您应该使用sort_by

@sorted_coll = @coll.sort_by { |obj| obj.created_at }

答案 1 :(得分:4)

@coll1 = Model1.all
@coll2 = Model2.all

@coll = @coll1 + @coll2

@sorted_coll = @coll.sort_by { |a| a.created_at } 

答案 2 :(得分:2)

你的@coll变量中有一个嵌套数组。像这样:http://codepad.org/jQ9cgpM1

尝试

@sorted = @coll1 + @coll2

然后排序。

答案 3 :(得分:0)

正如Jed Schneider所说,解决方案是:

@coll1 = Model1.all
@coll2 = Model2.all

@coll = @coll1 + @coll2 # use + instead of <<
相关问题