【问题标题】:Combining a scope on HABTM and belongs_to associations with OR将 HABTM 和 belongs_to 关联的范围与 OR 结合起来
【发布时间】:2019-06-25 11:29:38
【问题描述】:

我有以下型号:

class User < ApplicationRecord
  has_and_belongs_to_many :lists
end
class Workspace < ApplicationRecord
  has_many :lists, dependent: :nullify
end
class List < ApplicationRecord
  has_and_belongs_to_many :users
  belongs_to :workspace, optional: true

  scope :by_workspace, ->(workspace) { where(workspace: workspace) }
  scope :by_user, ->(user) { joins(:users).where(users: { id: user }) }
end

我需要的是一个by_workspace_or_user 范围,它返回属于给定工作区或给定用户的任何列表。我尝试使用or 组合这些,但没有运气。

【问题讨论】:

  • 你有没有尝试过这样的事情:List.where(worskpace: workspace).or(List.joins(:users).where(users: { id: user }))?或许,您可以使用现有范围:List.by_workspace(workspace).or(List.by_user(user))
  • 我有,我收到了ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins]
  • 然后尝试使用纯 SQL 版本:List.joins(:users).where("users.id = ? OR lists.workspace_id = ?", user.id, workspace.id)
  • 那个人做到了!如此干净和简单。我正在尝试更复杂的查询——我的 SQL 技能很烂。感谢您的时间和耐心。
  • 尝试使用left_outer_joins 而不是joins

标签: sql ruby-on-rails postgresql activerecord rails-activerecord


【解决方案1】:

您可以使用纯 SQL where 来实现:

List
  .left_outer_joins(:users)
  .where("users.id = ? OR lists.workspace_id = ?", user.id, workspace.id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多