首页 > 解决方案 > 我们如何在多重关系中使用或调节

问题描述

我正在尝试运行查询以获取用户是所有者或成员的任何项目。一个项目可以有一个用户作为所有者 (belongs_to) 或多个用户作为成员 (has_and_belongs_to_many)。

以下不会给出错误,但它不能正常工作:

Project.joins(:members).where(user: current_user).or(Project.joins(:members).where(:users  => { :id => current_user.id })).order('updated_at DESC')

以下给出了ArgumentError Exception: Relation passed to #or must be structurally compatible. Incompatible values: [:joins]错误:

Project.joins(:user).where(user: current_user).or(Project.joins(:members).where(:users  => { :id => current_user.id }))

标签: ruby-on-railsactiverecord

解决方案


您可能不得不求助于使用多个查询,这些or语句可能有些棘手。也许是这样的。

ids1 = Project.where(user_id: current_user.id).ids
ids2 = Project.joins(:members).where(users: { id: current_user.id }).ids

Project.where(id: [ids1, ids2].flatten)

推荐阅读