不同的加入导轨 [英] Distinct Join Rails

查看:117
本文介绍了不同的加入导轨的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

视频有很多活动

我想获得有计划在未来事件的所有影片。

I am trying to get all Videos that have Events scheduled in the future.

我这里面已经在那里了:

I have this which was already there:

named_scope :scheduled_in_future, :joins => :event, :conditions => ["event.scheduled_start > ? AND event.status = ?", Time.now.to_i, 'PENDING']

这工作,但如果同样的视频在未来有多个事件,它会给我重复的视频记录。当然,我可以通过数组并剔除重复的,但必须有一个SQL的方式来做到这一点。

This works, but if the same Video has multiple events in the future it will give me duplicate Video records. Sure I can go through the array and weed out the duplicates, but there has to be a SQL way to do it.

我试着在加入

:select => "DISTINCT(video.id)"

但它只返回,而不是整个记录的ID字段。

but it only returns the ID field instead of the whole record.

推荐答案

尝试使用:包括而不是:加入你不应该看到更多的重复的视频效果。

Try using :include instead of :joins and you should not see any more duplicate video results.

此外,你应该用一个lambda你named_scope,否则 Time.now 将被缓存在第一次使用它,你会开始得到不正确的结果。

Also, you should be using a lambda in your named_scope, otherwise Time.now will be cached the first time you use it and you'll start getting incorrect results.

named_scope :scheduled_in_future, lambda {
  { 
    :include => :events,
    :conditions => ["event.scheduled_start > ? AND event.status = ?", Time.now.to_i, 'PENDING']
  }
}

这篇关于不同的加入导轨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆