【问题标题】:How do I create an array based of values that are not in another array?如何基于不在另一个数组中的值创建一个数组?
【发布时间】:2020-04-29 20:21:36
【问题描述】:

这是我的 Teams-Controller.rb

    @my_teams = current_user.teams.all
    @available_teams = Team.where.not(@my_teams.all)
  end

我正在尝试显示用户当前尚未加入的所有团队。我有三个模型 Team、TeamMember 和 User。目的是将用户带到可用团队的 show 方法并允许他们加入团队。 团队模型 team.rb

class Team < ApplicationRecord
  has_many :team_members
  has_many :users, through: :team_members
end

用户模型user.rb

class User < ApplicationRecord

has_many :team_members
  has_many :teams, through: :team_members
end

团队成员模型

class TeamMember < ApplicationRecord
  belongs_to :user
  belongs_to :team
end

【问题讨论】:

    标签: arrays ruby-on-rails ruby controller


    【解决方案1】:

    试试这个方法

    @my_teams = current_user.teams
    @available_teams = Team.where.not(id: @my_teams.pluck(:id))
    

    基本上我们想要实现的是一个类似这样的 SQL 查询

    SELECT * 
    FROM teams
    WHERE id NOT IN (1, 2, 3)
    

    【讨论】:

    • 不得不将 my_teams.pluck 更新为 @my_teams,但除此之外,您已经成功了。谢谢
    • 嘿,我的荣幸 :)
    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2021-07-02
    • 2023-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多