如何编写两个具有冲突连接的作用域?
假设我有以下模型:
# video.rb
class Video < ActiveRecord::Base
has_many :collection_videos, :dependent => :destroy
has_many :collections, :through => :collection_videos
named_scope :in_collection_one,
:joins => :collection_videos,
:conditions => "collection_videos.collection_id = 1"
named_scope :in_foo_collections,
:joins => :collections,
:conditions => "collections.foo = true"
end
# collections.rb
class Collection < ActiveRecord::Base
has_many :videos, :through => :collection_videos
has_many :collection_videos, :dependent => :destroy
end
# collection_videos.rb
class CollectionVideos < ActiveRecord::Base
belongs_to :collection
belongs_to :video
end
如果我进行以下调用:
Video.in_collection_one.in_foo_collections
在 ActiveRecord 构造 SQL 查询后,我会收到一个错误,抱怨执行多个连接 - 它将尝试连接 :collection_videos 两次(错误,应该只连接一次)和 :collections 一次(这是正确的)。这可能是由 Rails 中的错误引起的,但我想知道是否有解决方法。
注意:我使用的是 Rails/ActiveRecord 版本 2.3.2
Let's say I have the following model:
# video.rb
class Video < ActiveRecord::Base
has_many :collection_videos, :dependent => :destroy
has_many :collections, :through => :collection_videos
named_scope :in_collection_one,
:joins => :collection_videos,
:conditions => "collection_videos.collection_id = 1"
named_scope :in_foo_collections,
:joins => :collections,
:conditions => "collections.foo = true"
end
# collections.rb
class Collection < ActiveRecord::Base
has_many :videos, :through => :collection_videos
has_many :collection_videos, :dependent => :destroy
end
# collection_videos.rb
class CollectionVideos < ActiveRecord::Base
belongs_to :collection
belongs_to :video
end
If I make the following call:
Video.in_collection_one.in_foo_collections
I will get an error after ActiveRecord has constructed the SQL query complaining about doing multiple joins - it will attempt to join on :collection_videos twice (wrong, should only join once), and :collections once (this is correct). This is likely caused by a bug in rails but I'm wondering if there is a way around it.
Note: I am using Rails/ActiveRecord version 2.3.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
:include
而不是:join
吗?请参阅此问题,了解某人使用:include
执行以下操作的示例加入。Could you use
:include
instead of:join
? See this question for an example of someone using:include
to do joins.