Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在rails中创建记录后如何延迟_Ruby On Rails_Ruby On Rails 3_Ruby On Rails 3.2_Rails Models - Fatal编程技术网

Ruby on rails 在rails中创建记录后如何延迟

Ruby on rails 在rails中创建记录后如何延迟,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.2,rails-models,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.2,Rails Models,基本上,我需要在_save::create ward之后立即创建一个关联 位置.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

基本上,我需要在_save::create ward之后立即创建一个关联

位置.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
这类工作,大多数时候它将创建或关联记录,但有时c.id将为零,因为self.ward\u id=c.id行是在创建新的ward之前执行的,因此self.ward\u id通常为零;/
任何解决这个问题的想法都会很有帮助:)

你不需要延迟。。。这样不行。在
创建之后
您就已经有了您的记录。更可能的情况是,该记录有时无法保存。您可以使用
。创建病房
(带有
)以在保存失败时引发错误。从API文档中:

创建联合会!(属性={})

与创建_关联相同,但如果记录无效,则引发ActiveRecord::RecordInvalid


当然,您需要捕获异常。。。或者不是。无论哪种方式,至少在这种情况下,你是在陈述你的期望(并在例外情况下强制执行它们)。

c.id为零可能比其他任何东西都更表明你的创建失败。您是否有验证或任何可能导致create_ward失败的内容?我假设ward是一个has_one relationship我认为如果您提供连接
ward
位置的代码将非常有帮助。很酷,谢谢您提醒我执行:)