My models
class Team < ActiveRecord::Base
has_many :team_players
has_many :players, :through => :team_players
end
class TeamPlayer < ActiveRecord::Base
belongs_to :team
belongs_to :player
end
- Teams can have a different number of players
- Players can be on many teams
- Retrieving a team_id if it already exists <- My problem
When creating a new team, I’m basically choosing multiple players in a nested form. Upon create, I need to check if a team with the exact player composition already exist.
Example:
- Team 1: A (id 1) and B (id 2)
- Team 2: A (id 1), B (id 2) and C (id 3)
Lets say I create a new team with A and B, then I need the query somehow tell me if it exists or not, by returning the team_id or something, or an empty result.
I’ve played around with queries similar to this, but with no satisfying result
SELECT *, count(id) as c FROM "team_players" WHERE player_id IN (1,3) GROUP BY team_id HAVING c = 2
I think you can do this in two steps:
That translates into this:
Given this in
team_players:The above query says
team_id = 2and there’s your exact match. The query you’re using gives you the teams that contain the players in question as a subset, not the teams that are set-wise equal to the players in question.If you only want to know if such a team exists then wrap that query in a
select_rowscall and you’re done:The
#{players.join(',')}interpolation assumes thatteam_exist?is being given an array of Fixnum so you’ll want to properly scrub your data in the caller or add aplayers = players.map(&:to_i)before theconnect.select_rowscall to scrub it insideteam_exist?.