我正在尝试进行基本的 belongs_to/has_many 关联,但遇到了问题。似乎声明类的外键列没有被更新。这是我的模型:
#
# 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
当我打开 rails 控制台时,我执行以下操作:
#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 列。不确定我在这里做错了什么。帮助表示赞赏。如果您需要更多信息,请与我们联系。