【问题标题】:ruby on rails: Order index page of a model (Topic) based on another model (Post)ruby on rails:基于另一个模型(帖子)的模型(主题)的订单索引页面
【发布时间】:2012-06-17 15:35:40
【问题描述】:

我有一个主题模型和一个帖子模型。一个Topic有很多Post,一个Post属于Topic。

我想根据每个主题的最新帖子显示主题的index 页面。最近的最后一个帖子是针对一个主题的,它将更多地显示在顶部。我基本上希望模拟常规论坛所做的事情。如果您回复一个主题,该主题会在索引页面中上升。

所以我需要根据每个主题的最后一篇文章的 *created_at* 以某种方式对主题进行排序。如何做到这一点?

topics_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

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

【问题讨论】:

    标签: ruby-on-rails sqlite associations


    【解决方案1】:

    Topic.includes(:posts).order('posts.created_at DESC') 怎么样

    【讨论】:

    • 谢谢。这是一种方便的方法。我做了includes 而不是include
    • 是的,我不记得两者之间的关系!
    【解决方案2】:

    我同意 Oscar,但对于您的情况,请务必考虑变量:

    :updated_at
    

    如果某些东西是在 2 年前创建的,然后在 5 分钟前更新,那并没有真正帮助解决这种情况。

    Topic.include(:posts).order('posts.updated_at DESC')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-20
      • 2015-11-16
      • 2013-04-23
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多