我有一个game
和两个team
。我希望POST
这样的事情可以/games
-
{"game":{"home_team":1,"away_team":2,"time":"Wed, 12 Aug 2015 08:08:08 -0500","winner":1,"home_score":2,"away_score":1}}
我的game.rb
模型看起来像这样 -
class Game < ActiveRecord::Base
belongs_to :home_team_id, :class_name => "Team"
belongs_to :away_team_id, :class_name => "Team"
belongs_to :winner_id, :class_name => "Team"
...
end
我的team.rb
模型看起来像这样 -
class Team < ActiveRecord::Base
has_many :home_games, class_name: "Game"
has_many :away_games, class_name: "Game"
has_many :winners, class_name: "Game"
...
end
game
的架构如下 -
create_table "games", force: :cascade do |t|
t.integer "home_team_id"
t.integer "away_team_id"
t.datetime "time"
t.integer "home_score"
t.integer "away_score"
t.integer "winner_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "games", ["away_team_id"], name: "index_games_on_away_team", using: :btree
add_index "games", ["home_team_id"], name: "index_games_on_home_team", using: :btree
add_index "games", ["winner_id"], name: "index_games_on_winner", using: :btree
我得到的错误是Team(#70124766940300) expected, got Fixnum(#70124749378140)"
答案 0 :(得分:0)
这里有一个基本设置缺失。
架构不应该是"home_team"
和"away_team"
,而是"home_team_id"
和"away_team_id"
同样在模型中,无需定义foreign_key: "home_team"
或foreign_key: "away_team"
。 Rails惯例(我相信)将假设belongs_to :home_team, :class_name => "Team"
具有"home_team_id"
如果您在数据库级别(架构)考虑它,数据库不会在游戏表中存储有关home_team
的所有信息。它只有一个home_game_id
,因此它引用了home_game
。这样,数据库就不需要为每个关联复制一堆数据。
修复后,Controller中可能还有其他错误,但错误消息告诉你的是它获取的是Team类而不是Fixnum,所以它可能会调用game.home_team
并执行某些操作它,但你只是从数据库中提取home_team ID,而不是关联。