Ruby Rails 3,混淆了';在创建之前:一些方法'。。。什么时候某个方法会起作用?

Ruby Rails 3,混淆了';在创建之前:一些方法'。。。什么时候某个方法会起作用?,ruby,callback,Ruby,Callback,我们有一个名为set_guids的模型助手(由几个不同的模型使用),它将self.theguid设置为随机字符串。我们已经使用它很长时间了,我们知道它是有效的 在我们创建的一个新模型“Dish”中 before_create :set_guids (NOTE: no other before/after/validation, just this) def do_meat_dish ( this is invoked by @somemeat.do_meat_dish in the

我们有一个名为set_guids的模型助手(由几个不同的模型使用),它将self.theguid设置为随机字符串。我们已经使用它很长时间了,我们知道它是有效的

在我们创建的一个新模型“Dish”中

before_create :set_guids    (NOTE: no other before/after/validation, just this)

def do_meat_dish
  ( this is invoked by @somemeat.do_meat_dish in the Dish contoller )
  ( it manipulated the @somemeat object using self.this and self.that, works fine)

  ( THEN sometimes it creates a new object of SAME MODEL type )
  ( which is handled differently) 
    @veggie = Dish.new
    @veggie.do_veggie_dish
end

def do_veggie_dish
  recipe_str = "add the XXXX to water"
  recipe_str.gsub!("XXXX", self.theguid)  *** the PROBLEM: self.theguid is nil 
end
只要我们执行
veggie=Dish.new
就不应该
veggie.guid
被初始化

注意,我们尚未保存新对象。。。但是在你创造之前,它应该已经完成了它的任务,对吗

这与在同一模型的方法内创建模型的新实例有关吗

使用@作为变量有什么关系吗


附加说明:如果我们注释掉试图访问self.theguid的行,其他一切都正常。。。只有before\u create set\u guids设置的值(假定)是nil,而不是guid。

before\u create
仅在对象第一次保存到数据库之前调用。这就是为什么会得到
nil

我建议您在初始化后使用
回调。但是要小心,因为无论文档是新的还是从db加载的,都会调用初始化后的
,这样每次获取文档时都会有新的GUID,这不是您想要的。所以我建议你做一些类似的事情:

def set_guids 
  return unless theguid.nil?
  .....
end
def theguid
  super || set_guids
end
作为另一种解决方案,如果不想更改上面的after_create回调,可以执行以下操作:

def set_guids 
  return unless theguid.nil?
  .....
end
def theguid
  super || set_guids
end

那你也该走了。

doh!谢谢对rails比较陌生的人有什么建议可以学习回调的细微差别、何时使用回调等?请阅读新的更新以了解这两种解决方案的影响。