0

我需要在我的数据库中选择 3 个移动最快的事件。我通过减去 (game_start - game_current) 得到最快的移动并取其绝对值。

这是我想要做的。显然语法不正确,只是为了让您了解我想要做什么。

@fast_moving = Event.where("(ABS(game_start - game_current)) > ?", 3)[0..2]

谢谢!

4

1 回答 1

1

你几乎在那里!

Event.where("(ABS(game_start) - ABS(game_current)) > ?", 3).limit(3)

.limit(3)将在 db 级别将结果限制为仅 3 个结果。

你可以做一个范围:

class Event < ActiveRecord::Base
  scope :moving_fast, lambda { |duration| 
                        where("(ABS(game_start) - ABS(game_current)) > ?", duration || 3) }

并像这样使用它:

@fast_events = Event.moving_fast.limit(3)
# or
@fast_events = Event.moving_fast(5)

(您可以将duration参数传递给范围)

于 2013-06-03T13:56:34.863 回答