简体   繁体   English

Rails 4 OR查询使用组和连接表

[英]Rails 4 OR query with join table using group and having

I have a Rails 4 query like this: 我有这样的Rails 4查询:

user.positions.where('positions.active = ? OR positions.deadline < ?', false, Date.current).joins(:cvs).where(cvs: {accepted: true}).group(:id).having('COUNT(cvs.id) = 3')

This now produces the following SQL query: 现在,将产生以下SQL查询:

SELECT `positions`.* FROM `positions` INNER JOIN `cvs` ON `cvs`.`position_id` = `positions`.`id` WHERE `positions`.`user_id` = 4 AND (positions.active = 0 OR positions.deadline < '2015-01-21') AND `cvs`.`accepted` = 1 GROUP BY id HAVING COUNT(cvs.id) = 3

What I actually need is to make the second where query an OR condition, but the query from above results in an AND condition. 我真正需要的是在第二个查询OR条件的地方,但是上面的查询导致AND条件。

I also tried the following: 我还尝试了以下方法:

user.positions.joins(:cvs).where('positions.active = ? OR positions.deadline < ? OR cvs.accepted = 1 GROUP BY id HAVING COUNT(cvs.id) = ?', false, Date.current, 3)

but this is converted by Rails to 但这是由Rails转换为

SELECT  `positions`.* FROM `positions` INNER JOIN `cvs` ON `cvs`.`position_id` = `positions`.`id` WHERE `positions`.`user_id` = 4 AND (positions.active = 0 OR positions.deadline < '2015-01-21' OR cvs.accepted = 1 GROUP BY id HAVING COUNT(cvs.id) = 3)

which throws an sql syntax error due to the closing parenthesis at the end. 由于结尾处的右括号而导致sql语法错误。 Without the opening and closing parenthesis or if putting the closing parenthesis after '2015-01-21' it would work. 没有开括号和闭括号,或者如果将闭括号放在'2015-01-21'之后,它将起作用。 But I don't know how to tell Rails not to put any parenthesis there. 但是我不知道如何告诉Rails不要在其中加上任何括号。

(What I actually want to query are all positions which are not active OR where deadline has already reached OR where a position has 3 accepted CV's) (我实际上要查询的是所有未激活的职位,或者截止日期已到,或者职位有3个已接受简历的职位)

ActiveRecord cannot do or but Arel can. ActiveRecord无法做到or但是Arel可以做到。 The amazing scuttle.io will solve your problem: 令人惊叹的scuttle.io将解决您的问题:

Position.select(Position.arel_table[Arel.star]).where(
  Position.arel_table[:user_id].eq(4).or(
    Position.arel_table[:active].eq(0).or(Position.arel_table[:deadline].lt('2015-01-21')).or(Cv.arel_table[:accepted].eq(1))
  )
).joins(
  Position.arel_table.join(Cv.arel_table).on(
    Cv.arel_table[:position_id].eq(Position.arel_table[:id])
  ).join_sources
).group(:id)

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

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