ActiveRelation (arel) 相当于 :from

发布于 2024-12-06 18:18:38 字数 577 浏览 1 评论 0原文

我的一个模型中有这个named_scope:

named_scope :latest_100,
            :from => '(select * from videos order by videos.created_at desc limit 0, 100) as videos'

它的目的是创建一个包含最后 100 个视频的池(将结果作为“视频”返回,以便其他范围在该数据集上运行),然后我可以在此之后链接范围并进行过滤该结果池中的记录。

# video.rb
named_scope :most_popular, :order => 'popularity'
named_scope :take_5, :limit => 5

# video_controller.rb
# it gets the latest 100 videos, then sorts those by popularity, and takes the top 5.
@videos = Video.latest_100.most_popular.take_5

Arel 有类似的说法吗?

I have this named_scope in one of my models:

named_scope :latest_100,
            :from => '(select * from videos order by videos.created_at desc limit 0, 100) as videos'

Its purpose is to create a pool of the last 100 videos (returning that results as 'videos' so the other scopes operate on that dataset), and then I can chain scopes after that and filter records out of that pool of results.

# video.rb
named_scope :most_popular, :order => 'popularity'
named_scope :take_5, :limit => 5

# video_controller.rb
# it gets the latest 100 videos, then sorts those by popularity, and takes the top 5.
@videos = Video.latest_100.most_popular.take_5

Is there an equivalent statement for Arel?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

歌入人心 2024-12-13 18:18:38

Arel 中有一个 .from() 方法。

我按以下方式使用它:

# video.rb
scope :latest_100, from('(select * from videos limit 100 order by created_at desc) as videos')
scope :most_popular, order('popularity')
scope :take_5, limit(5)

# video_controller.rb
@videos = Video.latest_100.most_popular.take_5

latest_100 将创建一个有效视频池,您可以从中提取最流行的前 5 个视频。

There exists a .from() method in Arel.

I used it in the following manner:

# video.rb
scope :latest_100, from('(select * from videos limit 100 order by created_at desc) as videos')
scope :most_popular, order('popularity')
scope :take_5, limit(5)

# video_controller.rb
@videos = Video.latest_100.most_popular.take_5

The latest_100 will create a pool of valid videos from which you can pull the top 5 most popular.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文