被Rails 4协会错误困惑

时间:2014-07-31 18:08:35

标签: ruby-on-rails-4 associations

我充实了新的Rails应用程序&我是第一次使用Rails 4。脚手架有一个单一的名称"为每个MVC定义的字段。

然后我创建了一个简单的迁移&第一个模特协会:

class Ability < ActiveRecord::Base
    belongs_to :player, class_name: "Player", foreign_key: "player_id"
end

class Player < ActiveRecord::Base
    has_many :abilities
end

控制台显示正确的字段。我可以保存东西:

> Ability.first
Ability Load (0.1ms)  SELECT  "abilities".* FROM "abilities"   ORDER BY "abilities"."id" ASC LIMIT 1
=> #<Ability id: 1, name: "Ability0", value: 50, created_at: "2014-07-31 16:41:59", updated_at: "2014-07-31 18:14:57", player_id: nil> 

> Player.first
Player Load (0.3ms)  SELECT  "players".* FROM "players"   ORDER BY "players"."id" ASC LIMIT 1
=> #<Player id: 1, name: "Player0", created_at: "2014-07-31 16:42:00", updated_at: "2014-07-31 16:42:00"> 

> Ability.first.player = Player.first
Ability Load (0.4ms)  SELECT  "abilities".* FROM "abilities"   ORDER BY "abilities"."id" ASC LIMIT 1
Player Load (0.2ms)  SELECT  "players".* FROM "players"   ORDER BY "players"."id" ASC LIMIT 1
=> #<Player id: 1, name: "Player0", created_at: "2014-07-31 16:42:00", updated_at: "2014-07-31 16:42:00"> 

> Ability.first.save!
Ability Load (0.4ms)  SELECT  "abilities".* FROM "abilities"   ORDER BY "abilities"."id" ASC LIMIT 1
(0.1ms)  begin transaction
(0.1ms)  commit transaction
=> true

但是保存并不想&#34;采取&#34;:

> Ability.first
Ability Load (0.4ms)  SELECT  "abilities".* FROM "abilities"   ORDER BY "abilities"."id" ASC LIMIT 1
=> #<Ability id: 1, name: "Ability0", value: 50, created_at: "2014-07-31 16:41:59", updated_at: "2014-07-31 18:14:57", player_id: nil>

我知道这是一件简单的事情,但我感到很沮丧。问题是什么?

1 个答案:

答案 0 :(得分:1)

您正在将playerAbility的实例相关联并保存完全不同的Ability 实例(没有关联的player)这就是为什么播放器没有与您的Ability实例映射的原因。

让我们完成以下步骤:

第1步

Ability.first.player = Player.first

在这里,您创建了一个Ability的匿名实例,该实例引用abilities表中的第一条记录,然后将其与players表中的第一条记录相关联。这都是 in-memory ,并且关联尚未保存在表格中。

第2步

Ability.first.save!

接下来,您将再次创建 Ability的新匿名实例,它指的是abilities表中的第一条记录。但它与步骤1中创建的实例无关。因此,当您进行防火保存时!在它上面,它不会保存任何东西,因为在这个例子中没有任何字段被更改。


你能做的是:

ability = Ability.first
ability.player = Player.first
ability.save!

在所有步骤中,您使用相同的实例进行更改。