开发者

Rails activerecord order by field in related table

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.


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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜