How to insert two associated instances in to corresponding tables by using a Migration?
I have two ActiveRecode model, Car and User, which has many-to-one association:
class Car < ActiveRecord::Base
has_many :users
...
end
class User < ActiveRecord::Base
belongs_to :car
...
end
And, I have two tables in database, cars and users. users table has attribute car_id
I would like to have a migration which will insert a car instance to the cars table, meanwhile, there will be a user instance created which has the association with the car instance and will then 开发者_运维知识库be inserted to the users table. How to do this in a migration?
That's by run this migration, both the car instance and its associated user instance will be stored in the corresponding tables in database.
I am using Rails 3.
example of migrations
class FillCarsAndUsers < ActiveRecord::Migration
def self.up
#if you have a Corresponding class for table
Corresponding.find(:all).each do |cor|
#save data
car = Car.create(...) #you may save old car id, if need "Car.create(:id => cor.car_id, ...)"
User.create(:car_id => car.id, ...)
...
User.create(:car_id => car.id, ...)
end
end
def self.down
end
end
Try like this
data = {'car1' => ['user1', 'user2'], 'car2' => ['user3'], 'car3' => ['user4']}
data.each do |car, users|
car_obj = Car.create(:name => car)
users.each do |user|
User.create(:name => user, :car_id => car_obj.id)
end
end
精彩评论