2015-12-02 45 views
0

我正在尋找一種方法,可以在更新記錄時在電子郵件字段的開始處生成一個隨機字符串。更新屬性時添加一個隨機字符串

def update 
    @user = User.find_by_id(4) 
    @user.email = #method to update email with random string 
end 

所以,如果我有電子郵件記錄[email protected],我想這樣來更新它:

[email protected] 

如何能在軌道做什麼?

+1

你有沒有檢查這個[問:如何最好地產生在Ruby中一個隨機字符串(http://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-在旁註)? –

+0

只是更新設置器 – apneadiving

+1

你打算用隨機字符串*一次*還是每次*更新預先填寫電子郵件? –

回答

4

可以使用SecureRandom庫:

@user.email = "#{SecureRandom.hex(10)}_#{user.email}" 
+0

我怎樣才能得到一個隨機字符串只在數字? – user4965201

+0

使用''%011d'%rand(1e10)'代替'SecureRandom.hex(10)'。要更改字符串中的數字位數,請在此處更改「e」後的數字:'1e10' –

+0

SecureRandom是[標準庫](http://ruby-doc.org/stdlib-2.2.0/libdoc/)的一部分securerandom/rdoc/SecureRandom.html),不需要ActiveSupport。 – steenslag

1
(1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join 

8是您想隨機生成的字符數。

-1

建立在你的應用程序控制器這樣一個動作:

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 
+2

將此方法添加到'before_update'將在每個更新上預先添加到當前的email_adress。產生'foo1_foo2_foo3_dipak @ gmail.com'。我懷疑這是有用的或必需的。您應該使用'before_create'來代替。 –

+0

'before_action'是控制器的一種方法,它與模型無關 –

+0

是的,但我認爲他們需要相同的功能。 –

2

爲什麼不使用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 

希望它能幫助!

+0

只是一件小事:我認爲作者如果問題想在電子郵件地址中加一個隨機字符串,而不是完全替換'@'前的整個字符串 –

+0

@YuryLebedev是的,可能是這種情況。但他沒有提到。可能是這種情況,他想在'@'之前替換。作者需要在此確認:( – Dusht

+0

是的,你說得對,他在開始時提到,他希望'在電子郵件開始時產生一個隨機字符串'。 – Dusht

-1

我希望這會幫助你。

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 
+0

這是如何增加現有答案的辦法? –