【发布时间】:2019-10-25 13:17:17
【问题描述】:
class User < ActiveRecord::Base
has_many :roles
has_many :allocations, class_name: 'Project', inverse_of: :user
end
class Role < ActiveRecord::Base
belongs_to :user
end
class Project < ActiveRecord::Base
belongs_to :user, inverse_of: :allocations
end
我想找到那些没有分配并且分配start_date小于今天的用户。
我需要从Role 对象的集合中找到它。我正在尝试为其定义一个范围。如何在单个活动记录查询中将这两个条件组合在一起?
我现在单独做。
为了找到没有分配的用户,我尝试了以下方法:
@roles.includes(user: :allocations).where({ allocations: { user_id: nil }})
@roles.includes(user: :allocations).group('user.id').having('count(user.allocations) = 0')
它们似乎都不适合我。
【问题讨论】:
-
第一个解决方案有什么问题?它是否返回角色而不是用户?如果是这样,只需使用
pluck选择所需的字段 -
ERROR: missing FROM-clause entry for table "allocations" -
我认为您可能还需要用户
references才能访问分配表。@roles.includes(...).references(user: :allocations)...。我相信没有它,它实际上并没有加入表格,只是急切地加载关联
标签: ruby-on-rails postgresql activerecord