Ruby on rails 如何在Rails和Postgresql中查找带有多个标记的帖子
我有Ruby on rails 如何在Rails和Postgresql中查找带有多个标记的帖子,ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,我有Post、Tag和PostTag型号。一篇文章有很多标签。我想找到的职位,是专门与一个以上的标签标签 has_many :post_tags has_many :tags, through: :post_tags 例如,给定此数据集: posts table -------------------- id | title | -------------------- 1 | Carb overload | 2 | Heart burn | 3 | Nice n
Post
、Tag
和PostTag
型号。一篇文章有很多标签。我想找到的职位,是专门与一个以上的标签标签
has_many :post_tags
has_many :tags, through: :post_tags
例如,给定此数据集:
posts table
--------------------
id | title |
--------------------
1 | Carb overload |
2 | Heart burn |
3 | Nice n Light |
tags table
-------------
id | name |
-------------
1 | tomato |
2 | potato |
3 | basil |
4 | rice |
post_tags table
-----------------------
id | post_id | tag_id |
-----------------------
1 | 1 | 1 |
2 | 1 | 2 |
3 | 2 | 1 |
4 | 2 | 3 |
5 | 3 | 1 |
我想找到标有tomato
和basil
的帖子。这应该只返回“Heart burn”帖子(id 2)。同样,如果我查询带有tomato
和potato
标记的帖子,它应该返回“Carb重载”帖子(id 1)
我尝试了以下方法:
Post.joins(:tags).where(tags: { name: ['basil', 'tomato'] })
SQL
这将返回所有三篇文章,因为所有文章都共享标记番茄。我也试过:
Post.joins(:tags).where(tags: { name 'basil' }).where(tags: { name 'tomato' })
SQL
这不会返回任何记录
如何查询带有多个标记的帖子?使用方法
。包括,如下所示:
Item.where(xpto: "test")
.includes({:orders =>[:suppliers, :agents]}, :manufacturers)
Post.for_tag("basil").for_tag("tomato")
的文档包括
您可能需要查看编写此类查询的可能方法。下面是一个使用1B在Rails中实现查询的可能选项,子查询方法
在PostTag
模型中定义一个查询,该查询将获取给定Tag
名称的Post
ID值:
# PostTag.rb
def self.post_ids_for_tag(tag_name)
joins(:tag).where(tags: { name: tag_name }).select(:post_id)
end
在Post
模型中定义一个查询,该查询将使用子查询结构获取给定标记
名称的Post
记录:
# Post.rb
def self.for_tag(tag_name)
where("id IN (#{PostTag.post_ids_for_tag(tag_name).to_sql})")
end
然后可以使用如下查询:
Item.where(xpto: "test")
.includes({:orders =>[:suppliers, :agents]}, :manufacturers)
Post.for_tag("basil").for_tag("tomato")
谢谢这很有效。但我对子查询方法有点不太熟悉。我发现了。虽然如何将其转换为活动记录语法是另一回事,但我在Rails中看到的连接别名实现的唯一方法是在joins命令中使用直接SQL。类似于PostTag.joins(“内部连接标记为t1 ON t1.tag\u id=post\u tags.tag\u id”)。其中(“t1.name=?”,“basil”)