Roa*_*nes 1 activerecord ruby-on-rails relational-database has-many-through
我有一个典型的标签和任何对象关系:说
class Tag < ActiveRecord::Base
attr_accessible :name
has_many :tagazations
has_many :projects, :through => :tagazations
end
class Tagazation < ActiveRecord::Base
belongs_to :project
belongs_to :tag
validates :tag_id, :uniqueness => { :scope => :project_id }
end
class Project < ActiveRecord::Base
has_many :tagazations
has_many :tags, :through => :tagazations
end
Run Code Online (Sandbox Code Playgroud)
这里没什么特别的:每个项目都用一个或多个标签标记.
该应用程序具有搜索功能:您可以选择某些标签,我的应用程序应该显示所有标记有所有提及标签的项目.所以我得到了一个必要的tag_ids数组,然后遇到了这么简单的问题
要做到这一点你要采取共同的优势一个查询双不存在 SQL查询,基本上不会找到所有Y X.
在您的实例中,您可能会这样做:
class Project < ActiveRecord::Base
def with_tags(tag_ids)
where("NOT EXISTS (SELECT * FROM tags
WHERE NOT EXISTS (SELECT * FROM tagazations
WHERE tagazations.tag_id = tags.id
AND tagazations.project_id = projects.id)
AND tags.id IN (?))", tag_ids)
end
end
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用count,group和having,虽然我怀疑第一个版本更快但可以随意进行基准测试:
def with_tags(tag_ids)
joins(:tags).select('projects.*, count(tags.id) as tag_count')
.where(tags: { id: tag_ids }).group('projects.id')
.having('tag_count = ?', tag_ids.size)
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
535 次 |
| 最近记录: |