Ruby on rails 将select distinct sql语句转换为activerecord

Ruby on rails 将select distinct sql语句转换为activerecord,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,将此SQL语句转换为activerecord/ruby友好代码时遇到问题。请注意,结束日期实际上是DateTime.now SELECT DISTINCT events.id FROM events, channels WHERE events.channel_id = channels.id AND events.end_at >= '2015-02-11 22:55:04' ORDER BY start_at ASC, id ASC LIMIT 40 建议 编辑:这个问题的最初起因是

将此SQL语句转换为activerecord/ruby友好代码时遇到问题。请注意,结束日期实际上是DateTime.now

SELECT DISTINCT events.id FROM events, channels
WHERE events.channel_id = channels.id AND events.end_at >= '2015-02-11 22:55:04'
ORDER BY start_at ASC, id ASC LIMIT 40
建议

编辑:这个问题的最初起因是mysql不支持我正在开发的应用程序的子查询中的嵌套限制。因此,分页+此查询导致错误:

# channels is an activerecord relation, order_by_schedule is a scope
Event.where(:channel_id => channels).where{ end_at >= DateTime.now }.order_by_schedule.limit(channels.count * event_limit)

我认为您不需要加入
频道
,因为您根本不使用它们:

Event.select('DISTINCT id')
      where('end_at >= NOW()').
      order('started_at, id').
      limit(40)

如果你不使用它,为什么要加入频道?我在上面做了一个快速编辑。。。我认为我的sql语句实际上是不正确的,但我已经说明了最初的问题。