ruby-on-rails - Rails : Setting attribute in after_create

标签 ruby-on-rails activerecord callback

我希望ActiveRecord使用回调自动设置一些数据库字段。

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。我做错什么了?

最佳答案

before_createBase.save之前被调用,因为您未保存它不会被调用。

编辑:

class Product < ActiveRecord::Base
   before_create :set_locale
   def set_locale
      self.locale = I18n.locale
   end
end

有了这个功能,您的 Controller 就会按您的意愿工作。
@product = Product.create # before_create will be called and locale will be set for the new product

关于ruby-on-rails - Rails : Setting attribute in after_create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2327253/

相关文章:

php - CodeIgniter - 确保 activerecord where 语句有一个条件

design-patterns - 是否存在处理回调机制的设计模式?

ajax - 当数据类型为 'script' 时,jQuery ajax 调用不会启动回调

callback - Protobuf RPC 回调

iOS 接入点 : Transferring Certificates

ruby-on-rails - attribute.present 有什么区别?和属性?

ruby-on-rails - 在 Rails 中,您能否在 primary_key 和 foreign_key 具有不同数据类型的两个模型之间建立关联?

ruby-on-rails - Rails 4 表单 - 在一个表中创建记录并在另一个表中更新记录。如何?

mysql - 为什么 active_storage :install's migration (v5. 2.1) 运行时会生成无效的 MySQL 语法?

ruby-on-rails - UTF-8 问题中的 Rails ActiveRecord 无效字节序列