Rails:在after_create中设置属性

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

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未设置。 我做错了什么?

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

编辑:

 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 

使用before_create设置默认值。 请记住:保存到数据库会触发after_create 。 使用after_create只会初始化内存中的值,并且需要额外的保存才能将初始化值提交到数据库。

乔伊所说的是after_create不起作用。

使用before_create