Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Rails migration to raw SQL

How can I convert this migration to raw sql? or Can I convert?

class AddUnsubscribeTokenToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :unsubscribe_token, :string, :unique => true
    User.all.each do |user|
        user.unsubscribe_token = ActiveSupport::SecureRandom.hex(18)
    end
  end
  def self.down
    remove_column :users, :unsubscribe_token
  end
end
like image 439
Johnny Cash Avatar asked Feb 16 '13 20:02

Johnny Cash


2 Answers

AFAIK you can't convert a single migration into SQL, but you can have ActiveRecord output your schema in SQL instead of Ruby.

# in config/application.rb

config.active_record.schema_format = :sql

This will give you SQL output in your db/schema instead of the Ruby DSL. But neither format will include the snippet of code setting the user token.

Also, it's considered a Bad Idea to include DB modifying code like that in your migration. For example what happens if you get rid of or rename the model, when that migration runs it will fail. At least wrap it in a check for the model. or a begin/rescue/end

if defined? User
  User.all.each do |user|
    user.unsubscribe_token = ActiveSupport::SecureRandom.hex(18)
  end
end

or

begin
  User.all.each do |user|
    user.unsubscribe_token = ActiveSupport::SecureRandom.hex(18)
  end
rescue
end

And lastly, that snippet is not going to do what you intended since your not saving the model after setting the token, either use update_attributes or call user.save

like image 145
Cluster Avatar answered Sep 28 '22 06:09

Cluster


I stumbled upon a very nice article, describing how this can be achieved via a custom rake task.

like image 45
Alexander Popov Avatar answered Sep 28 '22 06:09

Alexander Popov