如何在Rails中以编程方式将数据添加到模型的has_many关系中?

时间:2015-03-12 02:53:05

标签: ruby-on-rails ruby activerecord

在这个应用程序中我有三个模型 - 玩家,团队和轮次。

class Player < ActiveRecord::Base
  has_and_belongs_to_many :teams
end

class Team < ActiveRecord::Base
  has_and_belongs_to_many :players
  belongs_to :round
end

class Round < ActiveRecord::Base
  has_many :teams
end

在每轮比赛中,将根据发送的球员数量生成不同数量的球队(球员要坚持不懈,但在每一轮中你可以选择那次实际参加比赛的球员)。创建团队后,他们将填充此轮次的玩家列表。

在我的RoundsController中,我设置了一个方法,该方法在新Round的create动作中被调用。

def createTeams
  totalPlayers = @players.length
  noOfTeams = totalPlayers/5

  while (noOfTeams > 0) do
    team = Team.new
    team.round = @round
    team.save
    noOfTeams -= 1
  end

  i = totalPlayers - 1

  while (i >= 0) do
    @round.teams.each do |team|
      player = @players.at(i)
      player.team = team
      player.save
      i -= 1
  end
end

目前我无法将团队的轮次设置为当前轮次,因此我收到了“无法写入未知属性round_id”错误。我是以正确的方式来做这件事的吗?我是否正确设置了我的关系?我想我可以做一些像@ round.teams.build(团队)或@ round.teams.add(团队)......任何帮助表示感谢,抱歉,如果这是重复但我一直在寻找一会儿没有运气。

这是架构:

ActiveRecord::Schema.define(version: 20150310124456) do

create_table "players", force: :cascade do |t|
  t.string   "first_name"
  t.string   "surname"
  t.string   "email"
  t.string   "phone"
  t.integer  "goals"
  t.integer  "clean_sheets"
  t.integer  "wins"
  t.integer  "draws"
  t.integer  "losses"
  t.datetime "created_at",   null: false
  t.datetime "updated_at",   null: false
end

create_table "players_teams", id: false, force: :cascade do |t|
  t.integer "player_id"
  t.integer "team_id"
end

add_index "players_teams", ["player_id"], name:    "index_players_teams_on_player_id"
add_index "players_teams", ["team_id"], name:  "index_players_teams_on_team_id"

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

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

end

1 个答案:

答案 0 :(得分:0)

你错过了团队中的round_id

在迁移中,您只需使用

即可

add_column :teams, :round_id, :integer

解决这个问题。如果模型中有belongs_to,则需要这样的id。

并添加到一轮

@round.teams << team