2014-10-07 25 views
0

我有关于外键的这个问题 我想表中的外键叫做the_zombie_id 但是当我去控制台加载数据。 the_zombie_id不存在为Rails的模型定义外键关系似乎不起作用

class Zombie < ActiveRecord::Base 
    attr_accessible :age, :bio, :name 

    has_one :brain, :foreign_key => 'the_zombie_id' 
end 

class Brain < ActiveRecord::Base 
    attr_accessible :flavor, :status, :zombie_id 
    belongs_to :zombie 
end 

1.9.3-p547 :034 > brain=Brain.new => #<Brain id: nil, zombie_id: nil, status: nil, flavor: nil, created_at: nil, updated_at: nil> 
> 1.9.3-p547 :035 > brain.the_zombie_id NoMethodError: undefined method `the_zombie_id' for #<Brain:0xaa0193c> 
+0

编辑后,我看到你的表中有一个zombie_id(尊重约定)......为什么不使用它?只需删除两个模型中的foreign_key定义并正常使用它。 – Fer 2014-10-07 14:58:57

回答

0

在僵尸模式,

has_one :brain

您已经foreign_key在大脑表zombie_id

在大脑模型中,如果您想要使用the_zombie_id而不是zombie_id,请添加以下可添加到大脑模型中的代码。

alias_attribute :the_zombie_id, :zombie_id 
+0

朋友。如何在控制台中使用此名称? the_zombie_id – user3623442 2014-10-07 14:49:26

+0

1.9.3-p547:033> Brain.new =># user3623442 2014-10-07 14:51:07

+0

@ user3623442,只需查看我的更新回答 – 2014-10-07 15:11:23

0

你想foreign_key不是主键

class Zombie < ActiveRecord::Base 
    attr_accessible :age, :bio, :name 

    has_one :brain, :foreign_key => 'the_zombie_id' 
end 

此外,当你调用大脑想要z.brain如果您分配一个Zombiez

0

外键必须始终位于关联的“belongs_to”部分。在这种情况下,您的Brain模型应具有the_zombie_id属性。

您的模型应该看起来像下面;

class Zombie < ActiveRecord::Base 
    has_one :brain, :foreign_key => 'the_zombie_id' 
end 


class Brain < ActiveRecord::Base 
    belongs_to :zombie, :foreign_key => 'the_zombie_id' 
end 

当你的模型没有关注的钥匙的命名约定,你必须在这两个模型来指定,但属性必须在脑模型。

请注意,添加foreign_key选项不会奇迹般地将该字段添加到数据库表中。您必须通过迁移来创建它。