在 rails 模型中创建 before_create [英] before_create in rails model

查看:62
本文介绍了在 rails 模型中创建 before_create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Rails 模型 User,它有 nameemailhash 字段.

I have a rails model User that has name, email and hash fields.

我通过以下方式保存数据:

I save data to this by doing:

@u = User.create(:name=>'test', :email=>"test@mail.com")
@u.save

如何合并 before_create 回调,以便在保存记录之前哈希值通过以下代码获取哈希字符串:

How can I incorporate the before_create callback so that before saving the record the hash value gets a hash string by following code:

Digest::SHA1.hexdigest('something secret' + email)

我的 User 模型会是什么样子?

How will my User model look like?

class Employee < ActiveRecord::Base
   before_create :set_hash

   def set_hash 
      //what goes in here?
   end
end

推荐答案

您可以使用 self 关键字访问(和更改)当前模型的实例变量.

You can access (and alter) instance variables of your current model using the self keyword.

def set_hash
  self.email = Digest::SHA1.hexdigest('something secret' + self.email)
end

这篇关于在 rails 模型中创建 before_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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