将上面的查询仅在数据库上启动单个查询,否则将调用2个单独查询
find
和
select
.
。在这里,我有
secondary
flag是boolean
,如果是主要用户,则将是
false
。组织只有一个主要用户。
或可以在下面使用它?
# making it as an array.
users = User.where(organization_id: 1234).to_a
primary_user = users.find{ |user| !user.secondary }
secondary_users = users.select(&:secondary)
return primary_user, secondary_users
这是解决问题的更好方法。
如果组织只能让一个主要用户添加一个外键指向该用户。
class AddPrimaryUserToOrganizations < ActiveRecord::Migration[8.0]
def change
add_reference :organizations, :primary_user,
null: false,
foreign_key: { to_table: :users }
end
end
class Organization < ApplicationRecord
has_many :users
belongs_to :primary_user,
class_name: 'User',
inverse_of: :organizations_as_primary_user
end
class User < ApplicationRecord
belongs_to :organization
has_many :organizations_as_primary_user,
foreign_key: :primary_user_id,
class_name: 'Organization',
inverse_of: :primary_user
end
然后,您只需添加一个其他条款即可滤除主要用户:
orgs, users = Organization.arel_table, User.arel_table
User.where(organization_id: 1234)
.left_joins(:organizations_as_primary_user)
.where.not(users[:id].eq(orgs[:primary_user_id]))
生成以下查询
SELECT "users".* FROM "users"
LEFT OUTER JOIN
"organizations"
ON "organizations"."primary_user_id" = "users"."id"
WHERE
"users"."organization_id" = 1234
AND
"users"."id" != "organizations"."primary_user_id"