我想做一个基本的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