我已经设置了一个模型结构,它允许不同的模型通过 has_many ... :through ... 关联与文件模型关联,该关联也是多态的,因此文件可以属于许多不同的模型,不同的资源可以有许多文件。
然后文件模型属于一个附件模型,它是实际的文件,但我使用文件模型来跟踪不同的版本等等。附件模型知道文件是否是图像。
这是基本的模型结构:
class Resource < ActiveRecord::Base
has_many :file_associations, :as => :association
has_many :files, :through => :file_associations
...
end
class FileAssociation < ActiveRecord::Base
belongs_to :r_file
belongs_to :association, :polymorphic => true
...
end
class File < ActiveRecord::Base
has_many :file_associations
belongs_to :attachment
named_scope :images, lambda { { :include => :attachment,
:conditions => "attachments.type = 'AttachmentImage'" } }
...
end
然后,我使用此设置从具有作为图像的附件的特定资源中检索所有文件,如下所示:
@resource.files.images
当我检查由此生成的 SQL 查询时,它包含了将资源与 FileAssociation 连接两次的条件:
SELECT ....
FROM `files`
LEFT OUTER JOIN `attachments` ON `attachments`.id = `files`.attachment_id
INNER JOIN `file_associations` ON `files`.id = `file_associations`.file_id
WHERE
(
( `file_associations`.association_id = 1 ) AND
( `file_associations`.association_type = 'Resource' )
)
AND
(
( attachments.type = 'AttachmentImage' ) AND
(
( `file_associations`.association_id = 1 ) AND
( `file_associations`.association_type = 'Resource' )
)
)
如果我只尝试调用 @resource.files,则条件不会重复。
这当然按预期工作,但从查询来看,似乎我已经做了一些可以改进的事情,并且我尝试尽可能多地考虑性能。那么为什么会发生这种奇怪的事情,我可以做些什么来改进它呢?
作为记录,使用了 rails 2.3.5 和 mysql。
更新
我最近做了一个类似上面描述的设置,唯一的区别是没有多态关联,但是当我查看查询时,仍然是重复的条件。所以这不是问题的原因。
然后我还尝试从上述 named_scope 中删除 lambda。我意识到这有点不必要,因为我没有提供任何论据。所以范围最终看起来像:
named_scope :images, :include => :attachment, :conditions => "attachments.type = 'AttachmentImage'"
还是重复...
可能是时候开票了,但我正在考虑尽快迁移到 Rails 3,所以我想我可以等一下,看看会发生什么。
最佳答案
Note that in rails 3.0 'named_scope' is deprecated in favor of simply 'scope'
我不知道为什么 Rails 将条件加倍,这可能是错误或边缘情况。
您是否尝试过第二个 has_many 关联,如下所示:
class Resource < ActiveRecord::Base
has_many :file_associations, :as => :association
has_many :files, :through => :file_associations
has_many :images, :through => :file_associations,
:source => :file,
:include => :attachment,
:conditions => "attachments.type = 'AttachmentImage'"
...
end
关于sql - 为什么 Rails 在使用具有关联的作用域时会生成重复的 SQL 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4323097/