【问题标题】:How to add references to a model to use it twice with different name?如何添加对模型的引用以使用不同的名称两次?
【发布时间】:2018-10-16 15:26:27
【问题描述】:

我有两个模型 Game 和 Team。我希望每场比赛都有两支球队:主队客队。我还想访问 @game.hometeam@game.awayteam

游戏

 create_table "games", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.datetime "start_time"
    t.datetime "end_time"
    t.string "name"
    t.integer "admin_id"
    t.integer "stadium_id"
    t.integer "hometeam_id"
    t.integer "awayteam_id"
  end

团队

create_table "teams", force: :cascade do |t|
   t.string "name"
   t.integer "capacity"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
end

我的 Game 控制器,Team 是空的

has_one :hometeam , :class_name => 'Team' 
has_one :awayteam , :class_name => 'Team' 

【问题讨论】:

  • 切换 has_onebelongs_to

标签: ruby-on-rails ruby model associations


【解决方案1】:

首先,根据Rails API :has_one定义:

指定与另一个类的一对一关联。这种方法 仅当其他类包含外键时才应使用。如果 当前类包含外键,那么你应该使用 属于_to 代替。也可以看看 ActiveRecord::Associations::ClassMethods 关于何时使用的概述 has_one 以及何时使用 belongs_to。

所以你的游戏定义应该使用:belongs_to 来指定这种类型的关系。

其次,要指定要在关系中使用的属性,您必须设置:foreign_key 选项。

默认情况下是 猜测是带有“_id”后缀的关联名称。所以一个 定义 belongs_to :person 关联的类将使用 “person_id”作为默认:foreign_key。同样,belongs_to :favorite_person, class_name: "Person" 将使用外键 “favorite_person_id”。

所以根据你可以做的文档:

class Game
  belongs_to :hometeam, foreing_key: 'hometeam_id', class_name: 'Team'
  belongs_to :awayteam, foreign_key: 'awayteam_id', class_name: 'Team'
end

或隐含形式:

class Game
  belongs_to :hometeam, class_name: 'Team'
  belongs_to :awayteam, class_name: 'Team'
end

那么每个团队可以有很多场比赛:

class Team
  has_many :home_games, class_name: 'Game', foreign_key: 'hometeam_id'
  has_many :away_games, class_name: 'Game', foreign_key: 'awayteam_id'
end

【讨论】:

  • 好的。这行得通,但我在其他部分有冲突。如果我想使用 has_one 唯一的改变是我必须将 hometeam_id 和 awayteam_id 移动到团队?
  • 我明白了,我怎样才能对 has_many 做同样的事情?很抱歉垃圾邮件,但我想弄清楚。感谢您的宝贵时间,感谢您的帮助。
  • @MarkosTzetzis 我更新了答案以包含has_many 关系
猜你喜欢
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多