2013-10-11 15 views
0

如何保存用戶名的小寫版本?我正在嘗試做「How do I handle uppercase and lowercase characters in a custom url?」中所說的內容。如何保存小寫版本的用戶名?

我想在兩個不同的列中保存小寫字母和區分大小寫的用戶名版本。

謝謝。

+0

[字符串#downcase](HTTP://www.ruby-doc。 org/core-1.9.3/String.html#method-i-downcase) – iamnotmaynard

+0

如果你試圖做同樣的問題,你是否嘗試過使用這個問題的答案? – iamnotmaynard

+0

可能重複[如何處理自定義url中的大寫和小寫字符?](http://stackoverflow.com/questions/4220865/how-do-i-handle-uppercase-and-lowercase-characters-in-一個自定義URL) – iamnotmaynard

回答

1

您可以在您的模型中添加類似這樣的內容,其中lower_username是表格中的其他用戶名列。

#Simply populates the field on the database 

before_save :downcase_username 

#If you have validation of the username (ie must be a unique field), 
#you may want to assign the lowercase username before the validation occurs. 

before_validation :downcase_username 

創建私有方法來填充小寫username列

private 

def downcase_username 
    self.lower_username = self.username.downcase 
end 
+0

謝謝,它的工作原理:D – Boris

+1

在創建'downcase_username'時會被調用兩次。你只需要'before_save'什麼是創建和更新觸發器。 – spickermann

+0

@spickermann這是真的。我已經更新了答案。謝謝。 – kobaltz

0
@user.username = "AbCd" 
@user.lowercase_username = @user.username.downcase 
@user.save 
1
# in user model 
before_validation :generate_lowercase_username 

private 
    def generate_lowercase_username 
    self.lowercase_username = username.downcase 
    end 
相關問題