1

I have the following:

= select :client, :id, User.all.map {|u| [u.username, u.id]}, include_blank: "Add a client by username"

I'd like to exclude all records from User.all that match current_user.manager_users. The point is so that the select box doesn't show users that are already added to the manager_users array which is a has_many collection.

4

3 回答 3

4

你可以这样做:

= select :client, :id, User.where("users.id NOT IN (?)", current_user.manager_users.pluck(:client_id)).map {|u| [u.username, u.id]}, include_blank: "Add a client by username"

新的东西在这里:

User.where("users.id NOT IN (?)", current_user.manager_users.pluck(:client_id))
    .map{ |u| [u.username, u.id] }

current_user.manager_users.pluck(:client_id)部分将检索(仅在数据库级别)链接到 current_user 的 manager_users 的所有 client_ID。

希望这可以帮助!

于 2013-05-21T01:43:04.153 回答
1

你可以这样做:

# in your controller
ids = current_user.manager_users.pluck(:id)
@users = User.where("id not in (?)", ids).map { |u| [u.username, u.id] }

然后@users在表格中使用。

于 2013-05-21T01:43:14.507 回答
1

涉及 NOT IN 的答案本质上是低效的,因为您在只需要 1 个的情况下进行 2 个查询,并来回传递所有 ID。

我猜 manager_users 是用户的自我加入。就像是:

has_many :manager_users, class_name: User, foreign_key: :manager_id

您需要从另一个角度进行查询,只需应用与用于生成 current_user.manager_users 关联的相反逻辑即可。执行以下操作:

User.where( "manager_id <> ?", current_user.id )

将 manager_id 替换为数据库中正确的连接列。没有理由这需要 2 个查询

于 2013-05-21T02:17:07.263 回答