I am using rails 3.1 and ruby 1.9.3,Now i want to use uuid concept in
rails 3 for existing data
so i did like :-
create_table :posts, :id => false do |t|
t.string :uuid, :limit => 36, :primary => true
# old rails versions
self.id = UUIDTools::UUID.random_create.to_s
This is working for new data,now i want to migrate existing data with
relation.for uuid they are using datatype as string,in postgresql the
data type used for primary_key and foreign key is integer ,so if i am
trying to change foreign key integer to string it is throwing error.
Could you please tell me some example,how to do this.
By default, a table on PostgreSQL does not register UUID…
It might work only for new tables you create, because to Postgres use UUID you need say it when creating the table… for existing ones, it might not happen because the table on PostgreSQL may not have been created with the option to use Uuids.
You might need to write a migration or rake task for this purpose.
Migration may look like this.
class MigrateData < ActiveRecord::Migration
get_all_models.each do |model|
model.where('').find_each do |model_instance|
model_instance.update_attributes id: UUIDTools::UUID.random_create.to_s
Module.constants.select do |constant_name|
constant = eval constant_name
if not constant.nil? and constant.is_a? Class and constant.superclass == ActiveRecord::Base
This migration will iterate over all the models in your app and generate UUID for each single instance.
For single instance migration we could do like this,what to be done if i want to migrate single instance with the relation?
I could not understand that what do you mean by single instance migration with relation. Can you please elaborate more?
I have model called user.
class User < ActiveRecord::Base
like above i am having lots of association,now i want to migrate all the relation to uuid.
By looking at your code, I assume that you have these models in your application.
Event. If that’s true then you don’t have to worry about that. The migration, that I shared before, will iterate through all these models and
ID in every database table will be replaced with generated UUID.