结合 HABTM 的范围和 belongs_to 与 OR 的关联

Combining a scope on HABTM and belongs_to associations with OR

我有以下型号:

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 范围,returns 属于给定工作区或给定用户的任何列表。我试过使用 or 组合这些,但没有成功。

您可以使用简单的 SQL where 来实现:

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