简体   繁体   English

在Rails ActiveRecord中将where子句与join子句一起使用

[英]Using a where clause with join clause in Rails activerecord

I want to do a join query with a where clause, but I'm getting a syntax error. 我想使用where子句进行联接查询,但是出现语法错误。

What is the correct syntax for using a where clause with a joins? 将where子句与联接一起使用的正确语法是什么?

The Rails docs gives an example using a hash with a single join, but can't find one similar to my problem. Rails的文档给出了一个示例,该示例使用具有单个联接的哈希,但是找不到与我的问题类似的哈希。

Query: 查询:

User.joins("user_tags").joins("tags").where("tags.value <> 'single'")

Error: 错误:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "tags"
LINE 1: ...LECT "users".* FROM "users" user_tags tags...

You can define in your user model 您可以在用户模型中定义

has_many :user_tags
has_many :tags, through: :user_tags

and then just use 然后就用

User.joins(:tags).where.not(tags: { value: 'single' })

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

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