Rails 3.0.5 own_to 关联未更新声明类中的主键
我正在尝试做一个基本的“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 列未填充。不确定我在这里做错了什么。感谢帮助。如果您需要更多信息,请告诉我。
I am trying to do a basic belongs_to/has_many association but running into a problem. It seems that the declaring class's foreign key column is not being updated. Here are my models:
#
# 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
When I open rails console I do the following:
#This works as it should
c1 = Client.create(:name => 'Urban Coding')
u1 = c1.units.create(:name => 'Birmingham Branch')
The above gives me the correct results. I have a client and a unit. The unit has the client_id foreign key field populated correctly.
#This does not work.
c1 = Client.create(:name => 'Urban Coding')
u1 = Unit.create(:name => 'Birmingham Branch')
u1.client = c1
I feel the above should have the same effect. However this is not the case. I have a unit and a client but the units client_id column is not populated. Not sure exactly what I am doing wrong here. Help is appreciated. Let me know if you need more information.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只是没有保存 u1,因此不会更改数据库。
如果您希望在单个操作中分配并保存它,请使用 update_attribute
You're simply not saving u1, hence no change to the database.
If you want it assigned and saved in a single operation, use update_attribute
是的,我想如果你保存它,ID 就会被设置。
第一个语法要好得多。如果您不想立即执行保存操作(create 会为您执行此操作),则可以使用 build:
Yep, I think if you save it the ID will get set.
The first syntax is much better. If you don't want to do the save action right away, which create does for you, then use build:
这是可行的:
但另一种方法是更好的创建方法。
This works:
but the other way is the better way to create it.