Ruby on rails 使用包含的Post对象对Ruby数组进行排序
我有一个Ruby数组,其中包含Post对象(一个Mongoid模型),在方法中创建了一个Ruby on rails 使用包含的Post对象对Ruby数组进行排序,ruby-on-rails,ruby,arrays,sorting,mongoid,Ruby On Rails,Ruby,Arrays,Sorting,Mongoid,我有一个Ruby数组,其中包含Post对象(一个Mongoid模型),在方法中创建了一个created\u,返回一个Time对象。我想要的是使用该方法对该数组进行排序(该方法存在于数组中的每个元素上)。我尝试了@posts.sort_by{post | post.created_at},但没有成功。我怎样才能做到这一点?谢谢 编辑:数组的示例: [#,#] 编辑#2:我得到了@posts arra的以下信息: @posts=Array.new @user.following.each do |
created\u,返回一个Time
对象。我想要的是使用该方法对该数组进行排序(该方法存在于数组中的每个元素上)。我尝试了@posts.sort_by{post | post.created_at}
,但没有成功。我怎样才能做到这一点?谢谢
编辑:数组的示例:
[#,#]
编辑#2:我得到了@posts arra的以下信息:
@posts=Array.new
@user.following.each do | user|
user.posts.each do|p|
@posts我不知道为什么这里有一个数组。通常,使用Mongoid查询时,您应该有一个Mongoid::Criteria
实例,您可以desc(:created_by)
或asc(:created_by)
打开该实例进行排序
不过,我想不出任何原因sort\u by
对您不起作用,在我的应用程序上效果很好(只是在控制台上试用过)
UPD:
@user.following.each do |user|
user.posts.each do |p|
@posts << p
end
end
现在,您可以@posts.desc(:created_at)
UPD2:
@user.following.each do |user|
user.posts.each do |p|
@posts << p
end
end
此外,为了使代码更清晰,您可以在User
上定义posts\u,如下所示:
class User
def posts_from_following
following.map(&:posts).inject { |posts, post| posts.concat post }
end
end
然后,就这么做吧
@posts = @user.posts_from_following.desc(:created_at)
在控制器中。@code>@posts.sort\u by&:created\u at
@posts.sort_by &:created_at
@posts.sort {|a, b| a.created_at <=> b.created_at }
@posts.sort{a,b | a.created_at b.created_at}
我不是在查询它,而是在使用嵌入式文档。Post被嵌入到带有“has_many”的用户中,用户返回的集合是的。posts
也可以通过desc
/asc
进行排序。我在实际代码和控制台上尝试过它,但帖子没有得到排序:(这是控制台上的相关部分:Oops,一个打字错误,应该是@posts.desc(:created_at)
,而不是@posts.desc(:created_by)
。请尝试在:created_at
中使用:created_?另外,请参阅我在UPD2中提出的更惯用的变体。
@posts.sort_by &:created_at
@posts.sort {|a, b| a.created_at <=> b.created_at }