简体   繁体   English

Rails ActiveRecord通过命名范围中的标签查找问题

[英]Rails ActiveRecord finding questions by tag in named scope

I want the equivalent of SO search by tag, so I need an exists query but I also still need to left join on all tags. 我想要按标签进行SO搜索,所以我需要一个exists查询,但我仍然需要在所有标签上保持联接。 I've tried a couple of approaches and I'm out of ideas. 我尝试了几种方法,但没有主意。

The Qustion - Tag relationship is through has_and_belongs_to_many both ways (ie I have a QuestionTags joiner table) 问题-标记关系是通过has_and_belongs_to_many两种方式(即,我有一个QuestionTags连接器表)

eg 例如

Question.join(:tags).where('tag.name = ?', tag_name).includes(:tags)

I would expect this to do what I need but actually it just mashes up the includes with the join and I just end up with basically an inner join. 我希望它可以做什么,我需要的,但实际上它只是捣烂了includesjoin ,我刚刚结束了与基本内连接。

Question.includes(:tags)
   .where("exists (
               select 1 from questions_tags 
                where question_id = questions.id 
                  and tag_id = (select id 
                                  from tags 
                                 where tags.name = ?))", tag_name) 

This fetches the correct results but a) is really ugly and b) gives a deprecation warning as again it seems to confuse the includes with the join : 这样可以获取正确的结果,但是a)确实很丑陋,b)发出了弃用警告,因为它似乎再次混淆了includesjoin

DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: questions, tags) that are referenced in a string SQL sn ippet. 弃用警告:您似乎渴望加载在字符串SQL sn ippet中引用的表(问题,标签之一)。 For example: 例如:

 Post.includes(:comments).where("comments.title = 'foo'") 

Note I'm trying to write these as named scopes. 注意我正在尝试将它们写为命名范围。

Let me know if the question isn't clear. 如果问题不清楚,请告诉我。 Thanks in advance. 提前致谢。

OK, got it. 好的,我知道了。 I know no built in syntax to do it. 我知道没有内置语法可以做到这一点。 I have used an alternative before, You can do like this: 我以前使用过替代方法,您可以这样做:

Question.include(:tags).where("questions.id IN (
#{ Question.joins(:tags).where('tags.name = ?', tag_name).select('questions.id').to_sql})")

You can also join this subquery to your questions table instead of using IN. 您也可以将此子查询加入问题表,而不必使用IN。 Alternatively if You are not against adding gems and You are using Postgres, use this gem . 或者,如果您不反对添加gems,而您正在使用Postgres,请使用this gem It provides really neat syntax for advanced queries. 它为高级查询提供了真正精巧的语法。

使用preload而不是includes

Question.preload(:tags).where("exists ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM