0

我对一对多关系有一种我没有得到的行为,这绝对让我发疯。

这是模型1:

class Account < ActiveRecord::Base
  belongs_to :organization, :autosave => true
  validates :organization, :presence => true
end

这是模型2:

class Organization < ActiveRecord::Base
  has_many :accounts, :autosave => true
  validates :accounts, :presence => true
end

现在,在 Rails 控制台中:

>> acc = Account.new
>> org = Organization.new
>> org.accounts << acc

>> org.accounts
[#<Account id: nil, organization_id: nil, created_at: nil, updated_at: nil>]

>> acc.organization
nil

或相反:

>> acc = Account.new
>> org = Organization.new
>> acc.organization = org

>> acc.organization
#<Organization id: nil, created_at: nil, updated_at: nil>

>> organization.accounts
[]

这是正常行为吗?我应该手动更新关系的双方吗?!

4

2 回答 2

1

答案很简单,先保存对象

acc = Account.new
org = Organization.new 
acc.organization = org
acc.save
于 2012-09-26T10:03:20.967 回答
1

参考this使用build

org = Organization.new
acc = org.build_account.new
org.save
于 2012-09-26T10:03:55.407 回答