I have user model and I want to add unique string key to all user records.Column name should be unsubscribe_key.
Before migration user record :
id = 1
username = "text"
id = 2
username = "abc"
After migration user record :
id = 1
username = "text"
unsubscribe_key = "5HQdTSsNRY6YCodmzr"
id = 2
username = "abc"
unsubscribe_key = "Jlewfw0324Lwp0sefr"
command to create new model and table with columns : rails g model ModelName col_name1:string col_name2:integer col_name3:text ... command to add more columns under existing table: rails g migration AddColumnToModelName col_name4:string col_name5:integer ...
Well, the easy part is adding the new column. On the shell:
rails generate migration AddUnsubscribeKeyToUsers unsubscribe_key:string
rake db:migrate
Also, you'll want to make this new attribute accessible in your user model:
attr_accessible :unsubscribe_key #along with all your other accessible attributes
Next, you'll need to add the unique keys. You could write some SQL code for that, or create a ruby script you can run within the rails console.
module AddUniqueKeys
KeyGenCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
extend self
def addUnsubscribeKeysToAllUsers
users = User.all
users.each do |u|
u.update_attributes(:unsubscribe_key => generateKey(18))
end
end
def generateKey(keyLength)
key = ""
keyLength.times do
key += generateKeyCharacter
end
key
end
def generateKeyCharacter
KeyGenCharacters[rand(KeyGenCharacters.length)-1]
end
end
Now go back to the shell and type rails console
. On the ruby command line:
>>require "add_unique_keys.rb"
=> true
>>AddUniqueKeys.addUnsubscribeKeysToAllUsers
=> #Should print out array of users
If all goes well, your new column should be filled in with random strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With