如何在 Rails 中自动对 has_many 关系进行排序? [英] How do I automatically sort a has_many relationship in Rails?

查看:23
本文介绍了如何在 Rails 中自动对 has_many 关系进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个非常简单的问题,但我在任何地方都没有看到它的答案.

This seems like a really simple question but I haven't seen it answered anywhere.

在 Rails 中,如果您有:

In rails if you have:

class Article < ActiveRecord::Base 
  has_many :comments 
end 
class Comments < ActiveRecord::Base 
  belongs_to :article 
end

为什么你不能用这样的东西对评论进行排序:

Why can't you order the comments with something like this:

@article.comments(:order=>"created_at DESC")

如果您需要大量引用命名范围,甚至人们也会这样做:

Named scope works if you need to reference it a lot and even people do stuff like this:

@article.comments.sort { |x,y| x.created_at <=> y.created_at }

但有些东西告诉我它应该更简单.我错过了什么?

But something tells me it should be simpler. What am I missing?

推荐答案

您可以使用 has_many 本身的选项指定裸集合的排序顺序:

You can specify the sort order for the bare collection with an option on has_many itself:

class Article < ActiveRecord::Base 
  has_many :comments, :order => 'created_at DESC'
end 
class Comment < ActiveRecord::Base 
  belongs_to :article 
end

或者,如果您想要一种简单的、非数据库的排序方法,请使用 sort_by:

Or, if you want a simple, non-database method of sorting, use sort_by:

article.comments.sort_by &:created_at

使用 ActiveRecord 添加的排序方法收集:

Collecting this with the ActiveRecord-added methods of ordering:

article.comments.find(:all, :order => 'created_at DESC')
article.comments.all(:order => 'created_at DESC')

您的进展可能会有所不同:上述解决方案的性能特征会发生巨大变化,具体取决于您最初获取数据的方式以及您使用哪种 Ruby 来运行您的应用.

Your mileage may vary: the performance characteristics of the above solutions will change wildly depending on how you're fetching data in the first place and which Ruby you're using to run your app.

这篇关于如何在 Rails 中自动对 has_many 关系进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆