Rails:在after_create中设置属性

时间:2010-02-24 15:43:04

标签: ruby-on-rails activerecord callback

我希望ActiveRecord使用回调自动设置一些数据库字段。

class Product < ActiveRecord::Base
   after_create :set_locale
   def set_locale
      self.locale = I18n.locale
   end
end

在./script/console中我做

p = Product.create
p

未设置字段p.locale。我做错了什么?

3 个答案:

答案 0 :(得分:8)

before_create之前调用

Base.save,因为你没有保存它没有被调用。

编辑:

class Product < ActiveRecord::Base
   before_create :set_locale
   def set_locale
      self.locale = I18n.locale
   end
end

在你的控制器中使用它将按照你想要的方式工作。

@product = Product.create # before_create will be called and locale will be set for the new product

答案 1 :(得分:2)

使用before_create设置默认值。请记住:{<1}}在保存到数据库后被解雇。使用after_create只会初始化内存中的值,并且需要附加保存才能将初始值提交给数据库。

答案 2 :(得分:1)

Joey所说的是after_create不起作用。

使用before_create