我有两个对象:Team
和Player
。正如您可能猜到的那样,Team
有很多Players
且Player
属于某个团队。
我知道我们可以使用另一个模型Team_Players
建模这种关系,但我想关注这里的原始关系,正如我在网上看到的许多指南所示。
创建Player
时,很容易为它们分配Team.id
,因为它们只有一个,但相反 - has_many
- 更复杂。 Rails guide on associations仅显示模型文件,因此这是我的反思:
class Team < ActiveRecord::Base
has_many :players
end
现在,我希望能够做Team.first.players
之类的事情,并获得一个数组或其他内容,但我得到undefined method player for #<Team:0x>
,事实上在this video,我做看到开发人员做那样的事情。那我错过了什么?我有来制作交叉点模型吗?我想象不会因为has_many
是Rails中固有的。
创建表后,我在此迁移中将Team
的引用添加到Player
:
def change
add_reference :players, :team, index: true
add_foreign_key :players, :team
end
同样,由于有许多关系不能用单个列建模,我在迁移中避免了这一部分。这是Team.first.players
返回数组所需功能所必需的吗?
答案 0 :(得分:1)
这就是我为了让它发挥作用所做的一切:
rails new teams
- 后跟bundle
rails g model Team name:string player_count:integer
rails g model Player player_name:string player_number:integer
rails g migration add_team_id_to_players
:
class AddTeamIdToPlayers < ActiveRecord::Migration
def change
add_column :players, :team_id, :integer
end
end
rake db:migrate
以下是我的模特:
class Player < ActiveRecord::Base
belongs_to :team
end
class Team < ActiveRecord::Base
has_many :players
end
然后,在控制台中:
Team.create(name: "Cats", player_count:1).save
Player.create(player_name: "Ryan", player_number:1, team_id:1).save
然后瞧:
Team.first.players
返回:
Team Load (0.2ms) SELECT "teams".* FROM "teams" ORDER BY "teams"."id" ASC LIMIT 1
Player Load (0.1ms) SELECT "players".* FROM "players" WHERE "players"."team_id" = ? [["team_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Player id: 2, player_name: "ryan", player_number: 1, created_at: "2015-12-18 19:32:39", updated_at: "2015-12-18 19:32:56", team_id: 1>]>