I’m using rails v3.0.9 and Mysql database.
I’m migrating the tables with existing data.
I’ve users table and all other tables contains the user_id column and now i need seperate the users into two (users & customers) tables,
So i need to migrate the new customers table with existing users records where the user type with customer
I need to create a customers table and set the id of users records with user type as customer,
which will be easy instead of migrating many of other tables(which is used only by customers) by checking every record with user’s user type and assign the new id of customers table.
Tables looks like
users table:
id | name | ...
------------------------------
1 | aaa | ...
2 | bbb | ...
4 | ddd | ...
6 | fff | ...
customers table
id | name | ...
-------------------------------
3 | ccc | ...
5 | eee | ...
7 | ggg | ...
When i’m migrating users existing data
In my migration file
def up
create_table(:customers) do |t|
t.string :name
end
User.joins(:user_type).where(:user_type => {:type_name => 'customer'}).find_in_batches(:batch_size => 100){ |users|
users.each {|user|
customer = Customer.new
customer.id = user.id
customer.name = user.name
customer.save(:validate => false)
}
}
end
Also tried
Customer.create!(:id => user.id) instead of save method
Is this correct?
Is there any way to assign the primary id ?
If i’m going wrong give me some suggestion to do it in right way…
Mysql allow to insert the record with value of primary id column.
In Rails, you can execute any sql query by supplying to execute method
For example: