簡體   English   中英

Ruby on Rails中的多個外鍵

[英]Multiple Foreign Keys with Ruby on Rails

我有以下設置:

一個matchdays home_team_id ,其中有一列稱為home_team_id ,另一visitor_team_id和一個team表。

我的匹配模型如下所示:

class Match < ActiveRecord::Base

  belongs_to :home_team, class_name: "Team", foreign_key: :home_team_id
  belongs_to :visitor_team, class_name: "Team", foreign_key: :visitor_team_id
  belongs_to :matchday

  validates :home_team, presence: true
  validates :visitor_team, presence: true
end

像這樣的團隊模型:

class Team < ActiveRecord::Base
  has_many :matches
  has_many :player
end

現在變得棘手(至少對我來說)。 我希望能夠致電team.matches並獲得該團隊的所有比賽。 由於每個團隊都有主場比賽,也有在場比賽。

當前,我收到一個ActiveRecord::StatementInvalid錯誤,因為它正在尋找匹配表中的team_id列。

因此,如果我理解正確,那么您所需要的只是一種返回當前團隊正在參加的所有比賽的方法。 這應該可以解決問題:

class Team < ActiveRecord::Base
  has_many :player

  def matches
    Team.where(home_team_id => self.id, foreign_key => self.id)

    # This line will also work if you want to try it out.
    # Team.where("home_team_id = ?", self.id).where("foreign_key = ?", self.id)
  end
end

編碼愉快!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM