简体   繁体   中英

how to delay after creating record in rails

Basically i need to create an association right after_save: :create ward

Location.rb

 after_save :createward      

  def createward
    w = Ward.find_by_name(self.city)
    if w.nil?
      c = self.create_ward({:name => self.city})
      self.ward_id = c.id  #this line should be delayed because - c.id is called to soon. 
    else
      self.ward_id = w.id
    end
  end

This sort of works, most of the time it will create or associate records but, sometimes c.id will be nil because self.ward_id = c.id line is executed before new ward is created, thus self.ward_id is usually nil ;/ Any ideas how to solve this one would be helpful :)

You don't need a delay... it doesn't work that way. After the create you'll have your record already. It's more likely that the record isn't saving sometimes. You can use .create_ward! (with an ! ) to raise an error if save fails. From the API docs:

create_association!(attributes = {})

Does the same as create_association, but raises ActiveRecord::RecordInvalid if the record is invalid.

Of course you'd then need to trap the exception... Or not. Either way at least this way you're stating your expectations (and enforcing them with an Exception).

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