这似乎是一个非常简单的问题,但我在任何地方都没有看到它的答案.
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:
@articlements(:order=>"created_at DESC")如果您需要大量引用命名范围,甚至人们也会这样做:
Named scope works if you need to reference it a lot and even people do stuff like this:
@articlements.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:
articlements.sort_by &:created_at使用 ActiveRecord 添加的排序方法收集:
Collecting this with the ActiveRecord-added methods of ordering:
articlements.find(:all, :order => 'created_at DESC') articlements.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
发布评论