【问题标题】:rails migration for matches between 2 teams2支球队之间比赛的rails迁移
【发布时间】:2016-05-15 23:59:10
【问题描述】:

目前我是一名使用 ruby​​ on rails 的初学者,试图确定我的模型 MatchesTeams 之间的关系。

我希望我的匹配项引用Teams 表两次,一次用于homeTeam,另一次用于awayTeam。我想我最大的问题是,我是否在模型中错误地声明了关系?

目前我什至无法通过比赛叫出球队的名字。

我希望能够调用 Team.matches 来列出一支球队的所有比赛,无论是主队还是客队,并最终能够调用特定球队的主场或客场比赛。

我还希望能够调用 Match.teams/Match.homeTeam/Match.awayTeam 来列出特定比赛的球队。

这是我目前所拥有的:

匹配迁移

class CreateMatches < ActiveRecord::Migration
  def change
    create_table :matches do |t|
      t.references :homeTeam
      t.references :awayTeam
    end
  end
end

匹配模型

class Match < ActiveRecord::Base
    has_one :homeTeam, :class_name => 'Team'
    has_one :awayTeam, :class_name => 'Team'
end

团队模型

class Team < ActiveRecord::Base
    has_and_belongs_to_many :matches
end

提前致谢!

【问题讨论】:

    标签: ruby-on-rails migration relationship


    【解决方案1】:

    你可以这样做:

    class Match < ActiveRecord::Base
        belongs_to :hometeam, :class_name => 'Team'
        belongs_to :awayteam, :class_name => 'Team'
    
     #if you want to select all teams of a match, you can create a method
     def teams
      Team.find(self.hometeam_id, self.awayteam_id)
     end
    end
    
    class Team < ActiveRecord::Base
      has_many :home, class_name: 'Match', foreign_key: 'hometeam_id'
      has_many :away, class_name: 'Match', foreign_key: 'awayteam_id'
    end
    

    【讨论】:

    • 我是否能够合并我的Players 表并使用这些模型呼叫 Match.homeTeam/Match.awayTeam 的球员,或者我是否必须找到一种方法让球队属于比赛也一样?像Matchhas_many :teamshas_many :players, through: :teams一样思考
    • 您可以像Match.find(your_match_id).hometeam.players这样调用球员来查找所有主队球员,前提是您已经声明了球员和球队之间的关联。
    猜你喜欢
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    相关资源
    最近更新 更多