Rails:在after_create中设置属性

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

Joe*_*oey 9

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)

  • 这个答案是对的.ActiveRecord :: Base.create将触发一次保存调用,再次调用save将无法解决问题. (5认同)