【问题标题】:POSTing JSON to rails with IDs results in Error使用 ID 将 JSON 发布到 rails 会导致错误
【发布时间】:2015-11-05 18:05:05
【问题描述】:

我有一个game 和两个teams。我希望能够 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)"

【问题讨论】:

  • 你的控制器代码在哪里?
  • 发生这种情况是因为foreign_key 和association 具有相同的名称。你能改变你的参数名称吗?例如 - 你能把它设为 home_team_id: 而不是 home_team: 吗?将外键更改为 home_team_id

标签: ruby-on-rails ruby json activerecord rails-api


【解决方案1】:

这里缺少一个基本设置。

架构不应为"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 =&gt; "Team" 的外键为"home_team_id"

如果您在数据库级别(架构)考虑它,数据库不会在游戏表中存储有关home_team 的所有信息。它只有一个home_game_id,所以它引用了home_game。这样,数据库就不需要为每个关联复制一堆数据。

一旦这个问题被修复,Controller 中可能会出现其他错误,但该错误消息告诉您的是它获取的是 Team 类而不是 Fixnum,因此它可能在某处调用 game.home_team 并对其进行处理,但您只是从数据库中提取 home_team ID,而不是关联。

【讨论】:

  • 这行得通,我还必须更改我的 json 消息和允许的变量。
猜你喜欢
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 2020-11-01
  • 1970-01-01
相关资源
最近更新 更多