开发者

Rails 3.0.5 belongs_to association not updating primary key in declaring class

开发者 https://www.devze.com 2023-02-16 09:53 出处:网络
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:

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 :dateti开发者_StackOverflow社区me
#

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.


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

u1.update_attribute(:client, c1)


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:

c1 = Client.create(:name => 'Urban Coding')
u1 = c1.units.build(:name => 'Birmingham Branch')
# do stuff with u1
u1.save


This works:

c1 = Client.create(:name => 'Urban Coding')
u1 = Unit.create(:name => 'Birmingham Branch')

u1.client_id = c1.id

u1.save
c1.save

but the other way is the better way to create it.

0

精彩评论

暂无评论...
验证码 换一张
取 消