在我的方法中,我想检查用户是否只有一个股东,如果它应该返回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
也许这可以给你一个提示。我在项目中使用了类似的东西,我有这些模型:
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')
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 ....
首先,如果你从他的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关联