我想做一個基本的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列沒有填充。不確定我在這裏做錯了什麼。幫助表示讚賞。如果您需要更多信息,請與我們聯繫。
或設置客戶端後的'u1.save'。 – 2011-03-14 01:42:36
這是有道理的。傻我。謝謝一堆! – Trent 2011-03-14 01:44:06