获取每个类别的最后一个条目

时间:2022-09-25 15:43:15

I have a system that has Blog, BlogEntry and Category. Category has many blogs and BlogEntry belongs to a blog.

我有一个具有Blog,BlogEntry和Category的系统。类别有很多博客,BlogEntry属于博客。

I have a front page which displayes the latest blog entries. I would like to get the latest (say 5 latest) blog entries for each category so there is a equal share of categories on the front page at any given time (fashion and "pink blogers" are posting a lot. Two times a day at minimum!)

我有一个显示最新博客条目的首页。我想获得每个类别的最新(比如5个最新)博客条目,因此在任何给定时间首页上都有相同比例的分类(时尚和“粉红色的气球”发布很多。每天两次在最小!)

It is a Rails app and uses kaminari for pagination so I obviously would prefer a solution that supports kaminari (a activerecord::relation being returned).

它是一个Rails应用程序并使用kaminari进行分页,所以我显然更喜欢支持kaminari的解决方案(返回一个activerecord :: relation)。

I'm looking for something like this: Retrieve 2 last posts for each category. But rails/ActiveRecord spesific. I could possibly take the sql from that answer and make it fit my database scheme but I think that would only return an array and not an ActiveRecord::Relation.

我正在寻找类似的东西:为每个类别检索2个最后的帖子。但rails / ActiveRecord特别容易。我可以从该答案中获取sql并使其适合我的数据库方案,但我认为这只会返回一个数组而不是ActiveRecord :: Relation。

Is what I'm looking for even possible?

我正在寻找甚至可能吗?

Any feedback is greatly appreciated. :)

任何反馈都非常感谢。 :)

1 个解决方案

#1


0  

You could use named scopes to filter blogs based on when they're published.

您可以使用命名范围根据博客发布时间过滤博客。

scope :recent, lambda { where('created_at >= ?', Time.current) }
scope :recent, lambda { order("created_at DESC") }
scope :recent, conditions: ["category = "blog" and created_at < ?", Time.now]

#1


0  

You could use named scopes to filter blogs based on when they're published.

您可以使用命名范围根据博客发布时间过滤博客。

scope :recent, lambda { where('created_at >= ?', Time.current) }
scope :recent, lambda { order("created_at DESC") }
scope :recent, conditions: ["category = "blog" and created_at < ?", Time.now]