Rails Active Record Statement Invalid Undefined column

45 Views Asked by At

I'm completely new in using ruby on rails and active record. I cant seem to figure out why I keep getting this error. I am trying to delete soccer teams through the destroy method and it wont work. Here is what the full error says: ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column matches.team_id does not exist LINE 1: SELECT "matches".* FROM "matches" WHERE "matches"."team_id" ... ^ ): Each match has two teams and a team can have many matches and players, here's what the classes looks like:

class Team < ApplicationRecord
    has_many :players , dependent: :destroy
    has_many :matches, foreign_key: "team_id", dependent: :destroy
end
class Match < ApplicationRecord
  belongs_to :teamA, foreign_key: "team_id", class_name: "Team"
  belongs_to :teamB, foreign_key: "team_id", class_name: "Team"
end

class CreateMatches < ActiveRecord::Migration[7.0]
  def change
    create_table :matches do |t|
      t.references :teamA, foreign_key: { to_table: :teams }
      t.references :teamB, foreign_key: { to_table: :teams }
      t.index: :teams, :teams_id, unique: true
      t.boolean :state
      t.string :result

      t.timestamps
    end
  end
end

What seems to be the issue? I used foreign keys to try and make these associations work, since I saw a few posts that recommended it but it hasn't worked for me.

1

There are 1 best solutions below

1
SteveTurczyn On

As pointed out in the comments, there's no team_id column in you team but there is teamA_id and teamB_id and if you specify them seperately, you'll be able to call #destroy

class Team < ApplicationRecord
  has_many :players , dependent: :destroy
  has_many :matches_as_A_team, foreign_key: "teamA_id", class_name: 'Match', dependent: :destroy
  has_many :matches_as_B_team, foreign_key: "teamB_id", class_name: 'Match'. dependent: :destroy
end

But it's not a great design, to be frank. I'd suggest a different approach... perhaps a matches table, a teams table, and a join table 'matches_teams' that belongs to both a match and a team. You could put information about the team's role in the match in the join table itself (e.g. a boolean 'home' that's true for the home team, false for the away team.