如果您已经完成了邀请和用户的迁移,建议您将邀请生成过程放入自定义的Rake任务中。将迁移严格限制在表操作上是一个好习惯。
/lib/tasks/distribute_invitations.rake
namespace :db do
desc "Run all custom tasks"
task :import_all => [:distribute_invitations, :some_other_data_import]
desc: "Some other data import"
task :some_other_data_import => :environment do
puts "insert task code here"
end
desc: "Give existing user's invitations"
task :distribute_invitations => :environment do
for user in User.all
if user.invitation_id.nil?
invite = Invitation.create(:sender_id => <some id>, :recipient_email => <some email>, :token => <some token>, :sent_at => Time.now)
user.update_attribute(:invitation_id, invite.id)
puts "Updated user #{user.id} with invitation_id #{invite.id}"
else
puts "User already has an invitation_id"
end
end
end
end
在将用户表迁移到具有邀请ID的模式后,您可以运行以下命令:
rake db:distribute_invitations
您现有的用户将通过邀请ID创建并关联到邀请。
或者您可以运行所有任务:
rake db:import_all
在这种情况下,很可能只需要将它与用户迁移一起插入:
class AddInvitationID < ActiveRecord::Migration
def self.up
add_column :users, :invitation_id, :integer
for user in User.all
if user.invitation_id.nil?
invite = Invitation.create(:sender_id => <some id>, :recipient_email => <some email>, :token => <some token>, :sent_at => Time.now)
user.update_attribute(:invitation_id, invite.id)
puts "Updated user #{user.id} with invitation_id #{invite.id}"
else
puts "User already has an invitation_id"
end
end
end
def self.down
remove_colum :users, :invitation_id
end
end
:environment
依赖。在这种情况下,无法定义你的model。请更新以避免其他人复制你的代码时出现错误。 - shingara