如何编写两个具有冲突连接的作用域?

发布于 2024-10-10 15:57:35 字数 1074 浏览 9 评论 0原文

假设我有以下模型:

# 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梨涡 2024-10-17 15:57:35

您可以使用 :include 而不是 :join 吗?请参阅此问题,了解某人使用 :include 执行以下操作的示例加入。

Could you use :include instead of :join? See this question for an example of someone using :include to do joins.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文