Rails activerecord 按相关表中的字段排序
我有一个典型的论坛风格的应用程序。有一个 Topics
模型,其中 has_many
Posts
。
我想要使用 Rails 2.3.x 查询主题表并按该主题中的最新帖子进行排序。
@topics = Topic.paginate :page => params[:page], :per_page => 25,
:include => :posts, :order => 'HELP'
我确信这是一个简单的问题,但对谷歌来说并没有什么乐趣。谢谢。
I have a typical forum style app. There is a Topics
model which has_many
Posts
.
What I want to do using Rails 2.3.x is query the topics table and sort by the most recent post in that topic.
@topics = Topic.paginate :page => params[:page], :per_page => 25,
:include => :posts, :order => 'HELP'
I'm sure this is a simple one but no joy with Google. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对连接列进行排序可能是一个坏主意,并且在许多情况下将花费大量时间来运行。更好的方法是在创建新帖子时调整主题模型上的特殊日期字段:
然后您可以根据需要轻松地对
activity_at
列进行排序。添加此列时,如果您有要迁移的现有数据,您始终可以使用最高发布时间填充初始
activity_at
。Sorting on a joined column is probably a bad idea and will take an enormous amount of time to run in many situations. What would be better is to twiddle a special date field on the Topic model when a new Post is created:
Then you can easily sort on the
activity_at
column as required.When adding this column you can always populate the initial
activity_at
with the highest posting time if you have existing data to migrate.