2

I just have this simple setup:

class Team < ActiveRecord::Base
  has_many :players
  has_many :users, -> { uniq }, through: :players
end
class User < ActiveRecord::Base
  has_many :players
  has_many :teams, -> { uniq }, through: :players
end
class Player < ActiveRecord::Base
  belongs_to :team
  belongs_to :user

  validates :user_id, :uniqueness => { :scope => :team_id }
end

With this I can create multiple Teams with the same user combination by calling this twice:

Team.create(user_ids: ["1","2"])

How to make sure that there is not already another team with these users?

Chrisn
  • 88
  • 1
  • 7
  • Are you saying you want to make sure each team has a unique combination of users? – mike Aug 20 '14 at 20:50
  • Yes, if there already is a team with user1 and user2 i can't create a new team with this combination. – Chrisn Aug 20 '14 at 20:53
  • So would you want the following to work? `Team.create(user_ids: ["1","2"]); create(user_ids: ["1","2","3"])` Sorry, I am just trying to understand what exactly you want to achieve. Do you want users to be able to join multiple teams? – mike Aug 20 '14 at 21:41
  • For sure, a user can be member of multiple teams. This should be possible: Team.create(user_ids: ["1","2"]); create(user_ids: ["1","3"]) and this: Team.create(user_ids: ["1","2"]); create(user_ids: ["1","2","3"]) but not this: Team.create(user_ids: ["1","2"]); create(user_ids: ["1","2"]) – Chrisn Aug 20 '14 at 21:56

0 Answers0