Rails has_many未定义的关联方法

时间:2015-12-18 19:09:53

标签: ruby-on-rails activerecord

我有两个对象:TeamPlayer。正如您可能猜到的那样,Team有很多PlayersPlayer属于某个团队。

我知道我们可以使用另一个模型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返回数组所需功能所必需的吗?

1 个答案:

答案 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>]>