扶手:在after_create设置属性 [英] Rails: Setting attribute in after_create

查看:143
本文介绍了扶手:在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?

推荐答案

before_create 被称为之前 Base.save 的,因为你不保存它不获取调用。

before_create is called before Base.save, since your not saving its not getting called.

编辑:

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

这篇关于扶手:在after_create设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆