我正在使用 Ruby on Rails 3,我成功地使用了嵌套模型来保存模型\对象关联。
在我的用户模型文件中:
class User < ActiveRecord::Base
has_one :account
accepts_nested_attributes_for :account
validates_associated :account
end
在 @user.save
之后 我想检索刚刚创建的帐户 ID 并将该值保存在用户数据库表中。我需要它,因为我将使用 account_id
作为用户类的外键,但我不知道这是否可能。如果是这样,我该怎么做?
在我的用户模型中,我还尝试了以下操作:
before_create :initialize_user
def initialize_user
user_account = Account.create
self.account_id = user_account.id
end
但它不起作用。
更新
我试过了
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 值。
最佳答案
方法是错误的。当您拥有“has_one”关系时,它们的外键位于关联模型中。所以在你的情况下它会考虑在内。如果它接受帐户的嵌套属性。如果你正在写,那应该默认处理。
看看http://railscasts.com/episodes/196-nested-model-form-part-1还有另一部分,看看嵌套表单是如何工作的
关于ruby-on-rails - 如何检索刚刚使用嵌套方法创建的帐户 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5356665/