用或分隔多个连接

时间:2018-10-25 13:34:28

标签: ruby-on-rails

我需要一个查询,该查询将选择具有匹配条件的分配(组或仅分配)的所有用户。在SQL中这样做很容易,但是结果将是一个数组。我需要结果为ActiveRecord :: Relation,以便可以将更多范围应用于结果。

通常会这样-"SELECT * from users JOINS assignments on (assignments.user_id = users.id) WHERE assignments.id > 5 OR JOINS group_assignments on (group_assignments.user_id = users.id) WHERE group_assignments.id > 5)"

但是我真的不知道,如何使用“ joins”或“ includes”来实现-“ both_assignments”下的作用域实际上并不起作用,我也不知道为什么。

class User < ActiveRecord::Base
  has_many :assignments
  has_many :group_assignments

  scope :both_assignments, lambda {
   joins(:assignments).where(condition..)
     .or(joins(:group_assignments).where(condition...)
    }
end

class Assignment < ActiveRecord::Base
  belongs_to :user
end

class GroupAssignment < ActiveRecord::Base
  belongs_to :user
end

0 个答案:

没有答案