Rails中的复杂SQL查询?

时间:2016-04-20 08:27:04

标签: sql ruby-on-rails

我需要从所有用户组中选择不属于当前用户项目的组。

  1. 分组habtm项目
  2. 项目belongs_to user
  3. 分组habtm用户
  4. 问题是没有项目就可以存在一个组。我理解如何进行单独的简单查询:

    @groups = current_user.groups.includes(:groups_projects).where.('groups_projects.project_id' => nil)
    
    @groups = current_user.groups.includes(:groups_projects).where.not('groups_projects.project_id' => current_user.projects.ids)
    

    如何在一个查询中创建它?

    更新

    根据答案,我提出了查询:

    @groups = current_user.groups.includes(:groups_projects).where("'groups_projects.project_id' = ? AND 'groups_projects.project_id' NOT IN (?)", nil, current_user.project_ids)
    

    但现在这是一个错误:

    PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "groups_projects.project_id"
    

    更新2

    下面的答案很好,但它不适合我,所以我以不同的方式制作:

    @groups = current_user.groups - current_user.groups.joins(:projects).merge(current_user.projects)
    

    也许这不是正确的方法,但它确实有效。

1 个答案:

答案 0 :(得分:0)

where WHERE中的SQL表示基础SQL语句的.includes(:groups_projects).where('groups_projects.project_id = ? OR groups_projects.project_id NOT IN (?)', nil, current_user.projects.ids).references(:groups_projects) 部分。在你的情况下,它可能看起来像

scores.append((item, score))
output_file.write(scores.sort()[:20] + '\n')