我希望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。我做错什么了?
最佳答案
before_create在Base.save之前被调用,因为您未保存它不会被调用。
编辑:
class Product < ActiveRecord::Base
before_create :set_locale
def set_locale
self.locale = I18n.locale
end
end
有了这个功能,您的 Controller 就会按您的意愿工作。
@product = Product.create # before_create will be called and locale will be set for the new product
关于ruby-on-rails - Rails : Setting attribute in after_create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2327253/