简体   繁体   English

创建记录之前,模型中的自我ID-rails 3

[英]Self ID in model, before record is created - rails 3

I have some code in my Item model (very loosely) like such: 我的Item模型中有一些代码(非常宽松),例如:

def author_id=(xyz) 
  book = Book.find_by_author_id(xyz)
  book.author_id = self.id
end

self.id doesn't seem to be set though, when creating a new record...Any ideas? 创建新记录时似乎没有设置self.id ...有什么想法吗?

id is set to record only after it is saved to database. id设置为仅在将其保存到数据库后才进行记录。 So you could add a simple callback here 所以你可以在这里添加一个简单的回调

after_create (or after_save - whatever you need) do |record|
  book = Book.find_by_author_id(xyz)
  book.update_attributes :author_id => record.id
end

if self is a new_record? 如果selfnew_record? (not persisted in the DB), you won't be able to assign id like this, since there's no id yet. (不在数据库中保留),您将无法分配这样的ID,因为还没有ID。 However, it should be possible to set book.author to self . 但是,应该可以将book.author设置为self

If this is not your case, you should consider specifying your question a bit. 如果不是您的情况,则应考虑稍微说明一下您的问题。

When you create a new record, no ID is set yet because the object is not in the database yet. 创建新记录时,尚未设置ID,因为该对象尚未在数据库中。 You can test it with the instance method new_record?() . 您可以使用实例方法new_record?()对其进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM