【问题标题】:How to get latest comments from each post in Rails?如何从 Rails 中的每个帖子中获取最新评论?
【发布时间】:2017-08-07 13:50:04
【问题描述】:

我有一个标准的博客模型、用户、帖子和 cmets。如何查询自定义用户每个帖子的1条最新评论?

我知道我们可以通过帖子将用户与 cmets 联系起来,但这并不能让我知道它有什么帮助。

数据库结构

users: id, name, created_at, updated_at

posts: id, title, created_at, updated_at, user_id

comments: id, text, created_at, updated_at, user_id, post_id

【问题讨论】:

  • 您应该分享更多类似的表格结构或一些 ruby​​ 代码,才能完成这个问题。
  • Molfar,你怎么定义最新的?最后 5 厘米? 3 小时前的评论?就像@RaymondNijland 建议的那样,您应该添加表结构
  • 最后 - 我的意思是最近的,按某些字段排序,在这种情况下 - 按 created_at
  • @Molfar 你期望得到什么?什么样的结构?像这样的东西:[post1: [new_comments_post1], post2: [new_comments_post2], post3: []]。还是只有cmets?你说的最近是什么意思?你应该更清楚

标签: mysql ruby-on-rails activerecord rails-activerecord


【解决方案1】:

如果你的结构是user 有很多comments,如果你想先得到最新的,那么首先按照它的 created_at 对 cme​​ts 进行排序,如下所示:

user.order('created_at DESC').comments

在您的post 模型中:

def latest_comment
    comments.order('created_at DESC').first
end

然后像这样使用它:

Post.all.each do |post|
    post.latest_comment
end

【讨论】:

  • 此语句 cat 返回同一帖子的多个 cmets。我需要获得每篇帖子的最新评论。
  • 如果您只需要为每个帖子获取一条评论,您可以在帖子中定义一个方法,获取最新评论然后迭代到您将显示的每个帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2016-01-02
  • 2021-07-13
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多