Rails有效地找到只有一个股东的用户

问题描述 投票:0回答:2

在我的方法中,我想检查用户是否只有一个股东,如果它应该返回true(稍后在if块中使用它)。基本上它应该反映像User.find_by(id: user.id).shareholder.count < 1之类的东西,因为它用不必要的查询重载数据库(我有~30k用户的数据库)。

我在想的是用where创建查询,所以我有这个:

def one_shareholder?(shareholder)
  ShareholdersUser.where(user_id: shareholder.owner_id).
                   where.not(shareholder_id: shareholder.id).exists?
end

但我不知道如何实现查询,如果该用户只有一个股东,将会计算。我应该使用像find_each这样的东西吗?

编辑:

user has_many :shareholder

shareholder belongs_to :owner

ShareholdersUser belongs_to :user and :shareholder

ruby-on-rails ruby-on-rails-5
2个回答
1
投票

也许这可以给你一个提示。我在项目中使用了类似的东西,我有这些模型:

class Company < ApplicationRecord
  has_many :permits
end

class Permit < ApplicationRecord
  belongs_to :company
end

对于我只使用一个许可证的公司:

Company.joins(:permits).group('companies.id').having('count(company_id) = 1')


Maybe you can pluck the ids and use the array to check wether the company is in the array. For example:
ids_of_companies_having_one_permit = Company.joins(:permits).group('companies.id').having('count(company_id) = 1').pluck(:id)

然后检查:

if ids_of_companies_having_one_permit.include? company.id ....


This is the thread I followed: Find all records which have a count of an association greater than zero

0
投票

首先,如果你从他的ID找到用户,那么可以直接使用User.find(user.id)而不是User.find_by(id: user.id)

其次,正如您在问题中提到的那样,您希望if条件为true / false。

根据您的查询,我认为您已实施user has_many shareholder协会。

所以你可以直接在你的if条件下使用User.find(user.id).shareholders < 1,如下所示,

if User.find(user.id).shareholders.count < 1
     #do something...
end

注意:我在条件中使用了复数股东,因为我们有has_many关联

© www.soinside.com 2019 - 2024. All rights reserved.