Edgar Tomeyan
Edgar Tomeyan

Reputation: 13

Rails references with custom column name

Here are two models:

class Team < ApplicationRecord
  has_many :matches
end
# Model
class Match < ApplicationRecord
  belongs_to :home_team, class_name: 'Team', foreign_key: 'home_team_id'
  belongs_to :away_team, class_name: 'Team', foreign_key: 'away_team_id'
end

# Migration
class CreateMatches < ActiveRecord::Migration[5.2]
  def change
    create_table :matches do |t|
      t.references :home_team, references: :team, foreign_key: { to_table: :teams}
      t.references :away_team, references: :team, foreign_key: { to_table: :teams}

      t.timestamps
    end
  end
end

Now I want to access to matches of a certain team, so I do it like this:

Team.first.matches

But obviously, it doesn't work because there is no 'team_id' column in matches table. So, how to get access to all matches of a certain team?

Upvotes: 0

Views: 396

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14890

You can always just have your own method on the model.

class Team < ApplicationRecord
   def matches
     Match.where('home_team_id = :team_id OR away_team_id = :team_id', team_id: self.id)
   end
end

You will of course miss out on some goodies has_many provides, but you can use this easily in your views/controllers, with extra where or order as needed.

= Team.find(1).matches.where(...).order(...)

Upvotes: 1

Related Questions