gpt4 book ai didi

ruby - 不在数组中的 Rails

转载 作者:数据小太阳 更新时间:2023-10-29 08:30:56 24 4
gpt4 key购买 nike

我有一些帖子,每个帖子都有很多标签。

我需要创建一个查询来匹配没有数组中准确标签的帖子。

此外,它还应该返回所有在该查询中根本没有标签的帖子。

这是我尝试过的:

  query = posts.joins('LEFT JOIN post_tags ON post.id = post_tags.post_id')
no_tags = ['test', 'test1']
query = query.where('post_tags.name NOT IN (?) OR post_tags.name IS ?', no_tags, nil) if no_tags

这给了我所有没有标签的帖子,这是正确的,它也给了我没有指定标签的帖子,并且没有其他标签,这也是正确的.

问题是,如果一篇文章有​​多个标签,比如test, another,它会在查询中返回它,这不是我想要的行为。

我需要过滤掉这些帖子,如果帖子有一个标签在数组中,是否包含其他标签。

例子:

post1 has tag `test`
post2 has tag `another`
post3 has tags `test, another`
post4 has no tags

它应该返回:

[post2, post4]

但现在它返回:

[post2, post3, post4]

最佳答案

post_tags 加入一个有两个标签的 post 返回两行。

post_name   post_tag
test3 test
test3 another

您现在应该明白为什么“test3”包含在您的结果中了。对每一行结果进行检查,其中一个作为有效结果通过。

考虑做类似的事情

no_tags = ['test', 'test1']
query = query.where('post.id NOT IN (SELECT post_id FROM post_tags WHERE name IN (?))',
no_tags) if no_tags

关于ruby - 不在数组中的 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35204952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com