xpe*_*int 6 activerecord ruby-on-rails callback
我希望ActiveRecord使用回调自动设置一些DB字段.
class Product < ActiveRecord::Base
after_create :set_locale
def set_locale
self.locale = I18n.locale
end
end
Run Code Online (Sandbox Code Playgroud)
在./script/console我做
p = Product.create
p
Run Code Online (Sandbox Code Playgroud)
字段p.locale未设置.我做错了什么?
before_create之前被调用Base.save,因为你不保存它不获取调用.
编辑:
class Product < ActiveRecord::Base
before_create :set_locale
def set_locale
self.locale = I18n.locale
end
end
Run Code Online (Sandbox Code Playgroud)
在你的控制器中使用它将按你想要的方式工作.
@product = Product.create # before_create will be called and locale will be set for the new product
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19508 次 |
| 最近记录: |