Rails 3,对'before_create:some_method'感到困惑......什么时候some_method会做它的事情?

时间:2011-02-04 04:27:16

标签: 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 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.theguid初始化?

注意我们还没有保存新对象......但是before_create仍然应该做到了,对吗?

它是否与在同一模型的方法中创建模型的新实例有关?

是否使用@作为变量?

补充说明:如果我们注释掉试图访问self.theguid的行,其他一切正常......它只是由before_create set_guids设置的值(假设)为nil而不是guid。

1 个答案:

答案 0 :(得分:2)

只有在第一次将对象保存到数据库之前,才会调用

before_create。这就是你得到nil的原因。

我建议您使用after_initialize回调。但要小心,因为只要文档是新的或从db加载就会调用after_initialize,这样每次获取文档时都会有新的guid,这不是你想要的。所以我建议你做一些事情:

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

作为另一种解决方案,如果您不想更改上面的after_create回调,您可以执行以下操作:

def theguid
  super || set_guids
end

那也应该让你去。