在相关表中,Rails按字段顺序活动记录

时间:2022-04-08 22:49:07

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.

我想使用Rails 2.3做什么。x是查询主题表并根据该主题中最近的文章进行排序。

@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.

我确信这是一个简单的,但没有快乐的谷歌。谢谢。

1 个解决方案

#1


1  

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:

对已连接的列进行排序可能不是一个好主意,并且在许多情况下需要大量的时间来运行。最好是在创建新帖子时,在主题模型上创建一个特殊的日期字段:

class Post < ActiveRecord::Base
  after_create :update_topic_activity_at

protected
  def update_topic_activity_at
    Topic.update_all({ :activity_at => Time.now }, { :id => self.topic_id})
  end
end

Then you can easily sort on the activity_at column as required.

然后您可以根据需要在activity_at列上轻松排序。

When adding this column you can always populate the initial activity_at with the highest posting time if you have existing data to migrate.

在添加此列时,如果要迁移现有数据,则可以始终使用最高的发布时间填充初始的activity_at。

#1


1  

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:

对已连接的列进行排序可能不是一个好主意,并且在许多情况下需要大量的时间来运行。最好是在创建新帖子时,在主题模型上创建一个特殊的日期字段:

class Post < ActiveRecord::Base
  after_create :update_topic_activity_at

protected
  def update_topic_activity_at
    Topic.update_all({ :activity_at => Time.now }, { :id => self.topic_id})
  end
end

Then you can easily sort on the activity_at column as required.

然后您可以根据需要在activity_at列上轻松排序。

When adding this column you can always populate the initial activity_at with the highest posting time if you have existing data to migrate.

在添加此列时,如果要迁移现有数据,则可以始终使用最高的发布时间填充初始的activity_at。