我正在尋找一種方法,可以在更新記錄時在電子郵件字段的開始處生成一個隨機字符串。更新屬性時添加一個隨機字符串
def update
@user = User.find_by_id(4)
@user.email = #method to update email with random string
end
所以,如果我有電子郵件記錄[email protected]
,我想這樣來更新它:
[email protected]
如何能在軌道做什麼?
我正在尋找一種方法,可以在更新記錄時在電子郵件字段的開始處生成一個隨機字符串。更新屬性時添加一個隨機字符串
def update
@user = User.find_by_id(4)
@user.email = #method to update email with random string
end
所以,如果我有電子郵件記錄[email protected]
,我想這樣來更新它:
[email protected]
如何能在軌道做什麼?
可以使用SecureRandom
庫:
@user.email = "#{SecureRandom.hex(10)}_#{user.email}"
我怎樣才能得到一個隨機字符串只在數字? – user4965201
使用''%011d'%rand(1e10)'代替'SecureRandom.hex(10)'。要更改字符串中的數字位數,請在此處更改「e」後的數字:'1e10' –
SecureRandom是[標準庫](http://ruby-doc.org/stdlib-2.2.0/libdoc/)的一部分securerandom/rdoc/SecureRandom.html),不需要ActiveSupport。 – steenslag
(1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join
8是您想隨機生成的字符數。
建立在你的應用程序控制器這樣一個動作:
private
def generate_random_string
SecureRandom.urlsafe_base64(nil, false)
end
而且像這樣使用任何控制器,你想:
def update
@user = User.find_by_id(4)
@user.email = generate_random_string + @user.email
end
將此方法添加到'before_update'將在每個更新上預先添加到當前的email_adress。產生'foo1_foo2_foo3_dipak @ gmail.com'。我懷疑這是有用的或必需的。您應該使用'before_create'來代替。 –
'before_action'是控制器的一種方法,它與模型無關 –
是的,但我認爲他們需要相同的功能。 –
爲什麼不使用SecureRandom
?
require 'securerandom'
random_string = SecureRandom.hex # provide argument to limit the no. of characters
# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)
對於電子郵件之前追加,你可以這樣做
@user.email = "#{SecureRandom.hex(5))_#{@user.email}" # 5 is no. of characters
希望它能幫助!
我希望這會幫助你。
def update
@user = User.find_by_id(4)
@user.email = "#{generate_random_string(8)}_#{@user.email}"
## You can pass any length to generate_random_string method, in this I have passed 8.
end
private
def generate_random_string(length)
options = { :length => length.to_i, :chars => ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a }
Array.new(options[:length]) { options[:chars].to_a[rand(options[:chars].to_a.size)] }.join
end
這是如何增加現有答案的辦法? –
你有沒有檢查這個[問:如何最好地產生在Ruby中一個隨機字符串(http://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-在旁註)? –
只是更新設置器 – apneadiving
你打算用隨機字符串*一次*還是每次*更新預先填寫電子郵件? –