Ruby on rails RubyonRails:基于另一个模型(Post)的模型(主题)的顺序索引页
我有一个主题模型和一个帖子模型。一个主题有许多帖子,而一篇帖子属于主题 我想根据每个主题的最新帖子显示主题的Ruby on rails RubyonRails:基于另一个模型(Post)的模型(主题)的顺序索引页,ruby-on-rails,sqlite,associations,Ruby On Rails,Sqlite,Associations,我有一个主题模型和一个帖子模型。一个主题有许多帖子,而一篇帖子属于主题 我想根据每个主题的最新帖子显示主题的索引页面。最近一篇文章是针对某个主题的,它将更多地显示在顶部。我基本上希望模拟常规论坛的功能。如果您回复某个主题,该主题将在索引页中上升 所以我需要根据每个主题最后一篇文章的*created_at*排序主题。如何做到这一点 主题\u controller.rb def index @forum = Forum.find(params[:forum_id]) @topics = @f
索引
页面。最近一篇文章是针对某个主题的,它将更多地显示在顶部。我基本上希望模拟常规论坛的功能。如果您回复某个主题,该主题将在索引页中上升
所以我需要根据每个主题最后一篇文章的*created_at*排序主题。如何做到这一点
主题\u controller.rb
def index
@forum = Forum.find(params[:forum_id])
@topics = @forum.topics.find(:all, :order => "last_post_id DESC")
# last_post_id is a column of Topic that stores ID of the last post
end
post.rb
class Post < ActiveRecord::Base
belongs_to :topic
attr_accessible :content
end
class Post
topic.rb
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
belongs_to :forum
accepts_nested_attributes_for :posts, :allow_destroy => true
attr_accessible :name, :last_post_id, :posts_attributes
end
类主题:destroy
属于:论坛
接受\u嵌套的\u属性\u for:posts,:allow\u destroy=>true
属性可访问:名称,:上次发布\u id,:发布\u属性
结束
主题如何。包括(:posts)。顺序('posts.created_at DESC')我同意Oscar,但对于您的情况,请确保也考虑变量:
:updated_at
如果某个东西是在2年前创建的,然后在5分钟前更新,这对情况并没有什么帮助
Topic.include(:posts).order('posts.updated_at DESC')
非常感谢。这是一个方便的方法。我做了
include
而不是include
是的,我永远记不起两者之间的区别了!