Ruby-on-rails – rails add column to user model

migrationruby-on-rails

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"

Best Answer

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:

app/models/user.rb

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.

lib/add_unique_keys.rb

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.