一对多的关系行为

时间:2012-09-26 09:56:32

标签: ruby-on-rails

我有一种关于一对多关系的行为,我没有得到它,这肯定让我疯了。

这是模型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
[]

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

2 个答案:

答案 0 :(得分:1)

答案很简单,只需先保存对象

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

答案 1 :(得分:1)

参考this使用build

org = Organization.new
acc = org.build_account.new
org.save