Ruby on Rails - 活跃记录 - 关系 - 多对多

时间:2013-02-16 05:12:44

标签: ruby-on-rails ruby

短版本:

当我参加锦标赛时,这是有效的,但是当我参加锦标赛时,这是有效的。它给了我:

  <main>'irb(main):117:0> tournament.teams << team
(0.1ms)  begin transaction
(0.0ms)  commit transaction
Team Load (0.2ms)  SELECT "teams".* FROM "teams" WHERE "teams"."tournament_id" = 1
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: teams.tournament_id: SELECT "teams".* FROM "teams"  WHERE "teams"."tournament_id" = 1

长版:

我想在团队和锦标赛之间建立关系,这种关系是多对多关系。我知道我必须通过连接表来完成这一操作,该连接表在下面显示的第一部分中完成。从那里,我必须分别添加团队/锦标赛模型中显示的关联。

    class TeamTournamentJoinAttempt3 < ActiveRecord::Migration
  def up
    create_table :teams_tournaments, :id => false do |t|
        t.integer "tournament_id"
        t.integer "team_id"
    end
    add_index :teams_tournaments, ["tournament_id", "team_id"]
  end

  def down
    drop_table :teams_tournaments
  end
end

锦标赛模特:

class Tournament < ActiveRecord::Base
  has_and_belongs_to_many :teams
end

团队模型:

class Team < ActiveRecord::Base
  has_and_belongs_to_many :tournaments
end

现在我可以使用以下方法在rails控制台中找到一个团队和锦标赛:

tournament = Tournaments.find(1)
team = Teams.find(1)

然后我可以使用:

在两者之间建立关系
team.tournaments << tournament
    (0.1ms)  begin transaction
    (0.3ms)  INSERT INTO "teams_tournaments" ("team_id", "tournament_id") VALUES (1, 1)
    (123.1ms)  commit transaction

热潮,我认为一切正常。但是,当我尝试以另一种方式(tournament.teams << team)时,它不起作用给我以下错误:

tournament.teams << team
    (0.1ms)  begin transaction
    (0.0ms)  commit transaction
    Team Load (0.2ms)  SELECT "teams".* FROM "teams" WHERE "teams"."tournament_id" = 1
    ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: teams.tournament_id: SELECT "teams".* FROM "teams"  WHERE "teams"."tournament_id" = 1

1 个答案:

答案 0 :(得分:0)

在尝试TeamTournamentJoinAttempt3reload!关联后,看到belongs_to我的赌注是在Ruby控制台中没有使用has_one