ruby-on-rails - 我们如何在多重关系中使用或调节
问题描述
我正在尝试运行查询以获取用户是所有者或成员的任何项目。一个项目可以有一个用户作为所有者 (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 }))
解决方案
您可能不得不求助于使用多个查询,这些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)
推荐阅读
- cloud - akamai 和 cloudflare 之间的区别
- ios - 运行 pod install 时出错:如何解决这个问题?
- python - Plotly Stacked Bar Chart 文本注释问题
- excel - 对PHPSpreadsheet生成的表格进行排序时如何保持表格格式?
- microsoft-graph-api - 需要将外部用户添加到 Outlook 365 中的联系人组(不是 DL)
- nodes - 如何使用变量来修改 Node Red 中的 Browser Endpoint
- java - 摄取“大”输入文件(超过 1GB)的 apache 光束管道不会创建任何输出文件
- android - 为什么我的颤振应用程序在反复重新安装 java 和 gradle 后无法工作?
- javascript - 如何初始化依赖于相同条件的多个常量
- typescript - 为什么 Enum[Enum.member] 在 codepen.io typescript 游乐场未定义?