Johnny Cash
Johnny Cash

Reputation: 5147

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

Upvotes: 5

Views: 4768

Answers (2)

Alexander Popov
Alexander Popov

Reputation: 25005

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

Upvotes: 2

Cluster
Cluster

Reputation: 5626

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

Upvotes: 3

Related Questions