简体   繁体   中英

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

I have some code in my Item model (very loosely) like such:

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?

id is set to record only after it is saved to database. 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? (not persisted in the DB), you won't be able to assign id like this, since there's no id yet. However, it should be possible to set book.author to 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. You can test it with the instance method new_record?() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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