0

我想做一个基本的belongs_to/has_many关联,但遇到问题。看来声明类的外键列没有被更新。这里是我的模型:Rails 3.0.5 belongs_to关联没有更新声明类中的主键


# 
# Table name: clients 
# 
# id   :integer   not null, primary key 
# name  :string(255) 
# created_at :datetime 
# updated_at :datetime 
# 

class Client < ActiveRecord::Base 
    has_many :units 
    ... 
    attr_accessible :name 
end 

# 
# Table name: units 
# 
# id   :integer   not null, primary key 
# client_id :integer 
# name  :string(255) 
# created_at :datetime 
# updated_at :datetime 
# 

class Unit < ActiveRecord::Base 
    belongs_to :client 
    ... 
    attr_accessible :name 
end 

当我打开轨道控制台我做到以下几点:以上

#This works as it should 
c1 = Client.create(:name => 'Urban Coding') 
u1 = c1.units.create(:name => 'Birmingham Branch') 

给了我正确的结果。我有一个客户和一个单位。该单元具有正确填充的client_id外键字段。

#This does not work. 
c1 = Client.create(:name => 'Urban Coding') 
u1 = Unit.create(:name => 'Birmingham Branch') 

u1.client = c1 

我觉得上面应该有同样的效果。然而,这种情况并非如此。我有一个单元和一个客户端,但单元client_id列没有填充。不确定我在这里做错了什么。帮助表示赞赏。如果您需要更多信息,请与我们联系。

回答

3

你根本就没有保存u1,因此没有改变数据库。

如果你想它分配并保存在一个单一的操作,使用update_attribute

u1.update_attribute(:client, c1) 
+1

或设置客户端后的'u1.save'。 – 2011-03-14 01:42:36

+0

这是有道理的。傻我。谢谢一堆! – Trent 2011-03-14 01:44:06

0

这工作:

c1 = Client.create(:name => 'Urban Coding') 
u1 = Unit.create(:name => 'Birmingham Branch') 

u1.client_id = c1.id 

u1.save 
c1.save 

但另一种方式是更好的方式来创建它。

+0

不,这不是唯一的方法。而这仍然不能保存。 – 2011-03-14 01:42:58

+0

如果我将client_id作为可访问的属性,这将工作。我不想要这个。 – Trent 2011-03-14 01:43:03

+0

如果'client_id'通过'attr_protected'受到保护,就像你说的那样,这确实会起作用。 – 2011-03-14 02:27:03

2

是的,我想如果你保存它的ID将设置。

第一种语法好得多。如果您不想立即执行保存操作,那么可以使用以下版本创建:

c1 = Client.create(:name => 'Urban Coding') 
u1 = c1.units.build(:name => 'Birmingham Branch') 
# do stuff with u1 
u1.save 
+0

我明白了!非常感谢,一如既往! – Trent 2011-03-14 01:44:32