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