使用 ID 将 JSON 发布到 rails 会导致错误

POSTing JSON to rails with IDs results in Error

我有一个 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)"

这里缺少一个基本设置。

架构不应为 "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"

如果你从数据库层面(Schema)考虑,数据库并不存储游戏table中关于home_team的所有信息。它只有一个 home_game_id,所以它引用了 home_game。这样,数据库就不需要为每个关联复制一堆数据了。

修复后控制器中可能还有其他错误,但该错误消息告诉您的是它得到的是团队 class 而不是 Fixnum,因此它可能在某处调用 game.home_team 并用它做一些事情,但你只是从数据库中提取 home_team ID,而不是关联。