我正在使用Ruby on Rails 3,併成功使用嵌套模型以保存模型\對象關聯。如何檢索剛剛使用嵌套方法創建的帳戶ID?
在用戶模型文件,我有:
class User < ActiveRecord::Base
has_one :account
accepts_nested_attributes_for :account
validates_associated :account
end
後@user.save
我想找回剛剛創建的帳戶ID,並保存在用戶數據庫表該值。我需要這樣做,因爲我將使用account_id
作爲用戶類的外鍵,但我不知道它是否可行。如果是這樣,我該怎麼做?
在我的用戶模型,我也tryed如下:
before_create :initialize_user
def initialize_user
user_account = Account.create
self.account_id = user_account.id
end
,但它不工作。
UPDATE
我tryed這
class User < ActiveRecord::Base
belongs_to :account,
:class_name => "Account",
:foreign_key => "users_account_id"
end
class Account < ActiveRecord::Base
has_one :user,
:class_name => "User",
:foreign_key => "users_account_id"
end
,並保存新的帳戶。無論如何,在用戶數據庫表中,列users_account_id
是null
,因此foreign_key值不會自動保存。
'@ user.account.id'不起作用? – mway 2011-03-18 19:16:00
使用_...通常意味着該模型將具有主鍵。任何屬於belongs_to的模型通常都會包含外鍵。你有沒有在賬戶模式中做'belongs_to'來維持這種關係? – 2011-03-18 19:17:52
@mway我認爲我必須主要在控制器中使用它。也許在模型中我必須使用回調,但如果另一個人創建自己的用戶,那麼這個人可能會得到相同的account.id值?(!)無論如何,我想找到一些「直接的方式」。 – user502052 2011-03-18 19:19:53