2
短版本:
這適用於我team.tournaments但不是當我做tournaments.teams時。它給我:Ruby on Rails - 活躍記錄 - 關係 - 多對多
<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
現在我能做找到一個團隊,利用在軌控制檯比賽:
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
有趣。我複製了你的遷移和你的模型,它對我來說工作得很好。我能夠剷除任何一種方式(比賽進入team.tournaments或一支球隊進入tournament.teams)。你的錦標賽和團隊遷移是什麼樣的? – gerry3 2013-02-16 07:52:50
我只是做了一個硬重置,清除了所有內容,取代了我所有的遷移工作。我不知道以前有什麼錯。不過,我非常感謝你的幫助。我不知道如何標記答案,因爲它最初的工作原理但是如果有人讀這個,上面的代碼是一個體面的樣本,如何製作多對多,然後如何檢查它是否工作。 – gbam 2013-02-16 15:17:12