我希望 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 未设置。我做错了什么?
创建之前 http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002141之前被调用基础保存 http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002329,因为您没有保存,所以不会被调用。
Edit:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)