Rails:在after_create中设置属性 [英] Rails: Setting attribute in after_create
本文介绍了Rails:在after_create中设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望ActiveRecord使用回调自动设置一些数据库字段。
I would like ActiveRecord to set some DB field automatically using callbacks.
class Product < ActiveRecord::Base
after_create :set_locale
def set_locale
self.locale = I18n.locale
end
end
在./script/console中我
In ./script/console I do
p = Product.create
p
未设置字段p.locale。我做错了什么?
Field p.locale is not set. What did I do wrong?
推荐答案
编辑:
class Product < ActiveRecord::Base
before_create :set_locale
def set_locale
self.locale = I18n.locale
end
end
在你的控制器中,你将如何使用它。
With this in your controller will work how you want it to.
@product = Product.create # before_create will be called and locale will be set for the new product
这篇关于Rails:在after_create中设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文