【发布时间】: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