Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails add column to user model

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"
like image 968
Johnny Cash Avatar asked Feb 16 '13 20:02

Johnny Cash


People also ask

How do you add multiple columns in rails?

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 ...


1 Answers

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.

like image 104
Austin Mullins Avatar answered Oct 07 '22 20:10

Austin Mullins