Rails:在after_create中设置属性
我希望ActiveRecord使用回调自动设置一些DB字段。
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未设置。 我做错了什么?
在Base.save之前调用before_create ,因为你没有保存它没有被调用。
编辑:
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
使用before_create
设置默认值。 请记住:保存到数据库后会触发after_create
。 使用after_create
只会初始化内存中的值,并且需要额外的保存才能将初始化值提交到数据库。
乔伊所说的是after_create不起作用。
使用before_create
- 有人可以为pluginaweek – statemachine提供一个活跃的记录示例吗?
- 为什么ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:near“)”:语法错误:INSERT INTO“user_friendships”()VALUES()
- Ruby on Rails多态关系的优缺点
- NameError:has_many通过关系的未初始化常量
- 使用jsonb数组的Rails(postgres)查询
- 如何在ActiveRecord中进行自反的自我加入关系?
- 有没有办法确保ActiveRecord层次结构中每个记录有一个对象引用?
- 将默认ActiveRecord id从0更改为1000000
- Rails:将加密数据存储在数据库中