Ruby-on-rails rails 将列添加到用户模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14914659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails add column to user model
提问by Johnny Cash
I have user model and I want to add unique string key to all user records.Column name should be unsubscribe_key.
我有用户模型,我想为所有用户记录添加唯一的字符串键。列名应该是 unsubscribe_key。
Before migrationuser record :
迁移前用户记录:
id = 1
username = "text"
id = 2
username = "abc"
After migrationuser record :
迁移用户记录后:
id = 1
username = "text"
unsubscribe_key = "5HQdTSsNRY6YCodmzr"
id = 2
username = "abc"
unsubscribe_key = "Jlewfw0324Lwp0sefr"
回答by Austin Mullins
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
应用程序/模型/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.
接下来,您需要添加唯一键。您可以为此编写一些 SQL 代码,或者创建一个可以在 rails 控制台中运行的 ruby 脚本。
lib/add_unique_keys.rb
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:
现在回到 shell 并输入rails console. 在 ruby 命令行上:
>>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.
如果一切顺利,您的新列应填充随机字符串。
回答by Brian Petro
Try
尝试
$ rails g migration AddUnsubscribe_keyToUsers unsubscribe_key:string
Then
然后
$ rake db:migrate
回答by Johnny Cash
It's the solution.
这就是解决方案。
class AddUnsubscribeTokenToUsers < ActiveRecord::Migration
def self.up
add_column :users, :unsubscribe_key, :string, :unique => true
User.all.each do |user|
user.unsubscribe_token = ActiveSupport::SecureRandom.hex(18)
end
end
def self.down
remove_column :users, :unsubscribe_key
end
end
回答by Nikhil Thombare
In Rails 4.0 add single column or multiple column using easy way.. https://gist.github.com/pyk/8569812
在 Rails 4.0 中使用简单的方法添加单列或多列.. https://gist.github.com/pyk/8569812

