我对一对多关系有一种我没有得到的行为,这绝对让我发疯。
这是模型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
[]
这是正常行为吗?我应该手动更新关系的双方吗?!