Rails Migration Update existing records while creating entries in another table
I am trying to set up Beta Invites for my Rails application. I have an Invitation model and a User model.
User has one invitation_id. I am validating that user must have an invitation_id and it should be unique. I want to write a migration so that I can update my existing users to have an invitation_id.
Here is my invitation model:
# Table name: invitations
#
# id :integer not null, primary key
# sender_id :integer
# recipient_email :string(255)
# token :string(255)
# sent_at :datetime
# created_at :datetime
# updated_at :datetime
To guarantee uniqueness, I will have to create records in invitation table and also assign the corresponding ids to the user records.
Can开发者_如何学Go someone please suggest a migration for the same?
Thanks in advance!
If you already did your migration for your invitations and users, you should really put the invitation populating in a custom rake task. Always a good practice to keep your migrations strictly for table manipulations.
/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
After you do your migration to give your users table an invitation_id, you can run:
rake db:distribute_invitations
and your existing users will have invitations created and associated to them through invitation_id.
Or to run all your tasks you can do:
rake db:import_all
In this case it is very possible to just stick it in the migration with your User migrate:
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
精彩评论