保存 Rails 模型后,我想生成 ID 的 md5 散列并将其与对象一起保存在数据库中。
我的问题是,如何定义执行此操作的方法?我需要 ID 来进行计算,但是直到保存后才完成?
最佳答案
在模型中使用 after_create 回调来执行此操作。
class YourClass < ActiveRecord::Base
after_create :hash_it
private
def hash_it
self.md5_hashed = id.md5_your_hash_method
end
end
仅供引用,可用的 4 个“后”回调是:
after_validation
after_create
after_save
after_commit
关于ruby-on-rails - Rails,生成记录 ID 的 MD5 散列值并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8193480/