基本上我需要在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
这种工作在大多数情况下会创建或关联记录,但有时c.id将为nil,因为self.ward_id = c.id行是在创建新病房之前执行的,因此self.ward_id通常为nil; /任何想法如何解决这一问题将是有帮助的:)
您不需要延迟...那样行不通。之后,create
您将拥有自己的记录。记录有时可能没有保存。如果保存失败,可以使用.create_ward!
(带有!
)引发错误。从API文档:
create_association!(属性= {})
与create_association相同,但是如果记录无效,则引发ActiveRecord :: RecordInvalid。
当然,您需要捕获该异常…否则就不会。无论哪种方式,至少您要用这种方式陈述自己的期望(并使用Exception强制执行)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句