Rails的named_scopes与加盟 [英] Rails named_scopes with joins

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

问题描述

我试图创建一个使用加入named_scope,不过虽然生成的SQL看起来正确,其结果都是垃圾。例如:

I'm trying to create a named_scope that uses a join, but although the generated SQL looks right, the result are garbage. For example:

class Clip < ActiveRecord::Base      
  named_scope :visible, {
    :joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id", 
    :conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' "
  }

(剪辑是由一系列拥有的,一个系列属于显示,一个显示可可见或不可见)。

(A Clip is owned by a Series, a Series belongs to a Show, a Show can be visible or invisible).

Clip.all做:

Clip.all does:

SELECT * FROM `clips`

Clip.visible.all做:

Clip.visible.all does:

SELECT * FROM `clips` INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id WHERE (shows.visible = 1 AND clips.owner_type = 'Series' )

这看起来不错。但由此产生的剪辑模式的阵列包括一个ID,这不是在数据库中的一个片段 - 它拿起一个节目ID来代替。我在哪里去了?

This looks okay. But the resulting array of Clip models includes a Clip with an ID that's not in the database - it's picked up a show ID instead. Where am I going wrong?

推荐答案

的问题是,SELECT * - 查询拿起所有列从夹子,系列和显示,在该顺序。每个表都有一个id列,因此在结果中指定的列之间的冲突。最后一个id列拉了回来(从所示)将覆盖你想要的。你应该使用:选择选项的:联接,如:

The problem is that "SELECT *" - the query picks up all the columns from clips, series, and shows, in that order. Each table has an id column, and result in conflicts between the named columns in the results. The last id column pulled back (from shows) overrides the one you want. You should be using a :select option with the :joins, like:

named_scope :visible, {
  :select => "episodes.*",
  :joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id", 
  :conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' "
}

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

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