带连接的 Rails name_scopes
我正在尝试创建一个使用联接的named_scope,但尽管生成的SQL 看起来正确,但结果却是垃圾。 例如:(
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' "
}
剪辑属于系列,系列属于节目,节目可以是可见的或不可见的)。
Clip.all 的作用:
SELECT * FROM `clips`
Clip.visible.all 的作用:
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。 我哪里出错了?
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 does:
SELECT * FROM `clips`
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' )
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于“SELECT *” - 查询按顺序从剪辑、系列和节目中选取所有列。 每个表都有一个 id 列,这会导致结果中的命名列之间发生冲突。 最后一个 id 列(从显示中)拉回会覆盖您想要的列。 您应该将 :select 选项与 :joins 一起使用,例如:
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:
这是一个错误:
http://rails.lighthouseapp.com/projects/8994/tickets/1077-chaining-scopes-with-duplicate-
连接导致别名问题
This is a bug:
http://rails.lighthouseapp.com/projects/8994/tickets/1077-chaining-scopes-with-duplicate-
joins-causes-alias-problem