2

精简版:

这在我进行 team.tournaments 时有效,但在我进行 tours.teams 时无效。它给了我:

  <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
4

1 回答 1

0

看到我的赌注是在实验或关联后TeamTournamentJoinAttempt3不在 Ruby 控制台中使用。reload!belongs_tohas_one

于 2013-02-16T08:40:42.790 回答