Reputation: 38842
I am using Rails 3. I don't know if it is the rule of rails that inside migration, it seems I can not insert data into database table. If someone can confirm it is so.
I tried the following things:
I have two ActiveRecord model:
class Car < ActiveRecord::Base
has_many :users
...
end
class User < ActiveRecord::Base
belongs_to :car
...
end
I have generate a migration file, inside the migration I have:
def self.up
default_car = Car.new({:name => 'default_car'})
default_car.save() #I got 'false' here
User.create!(:car_id => default_car.id}) #I got default_car.id is null value
end
def self.down
default_car = Car.find({:name => 'default_car'})
default_user = User.find({:car_id=>default_car.id})
default_car.delete
default_user.delete
end
I got false when I trying to save the default_car to database, and my default_user have null car_id.
Is it because in migration, it is NOT allowed to store data into database??
Upvotes: 0
Views: 1533
Reputation: 83680
Ok, we've figgured out that there was some validation issues. So you would like to now, that you can skip validations:
default_car = Car.new({:name => 'default_car'})
default_car.save(false)
#=> true
Upvotes: 0
Reputation: 9754
You can create data in migrations, however it is probably best not to, use seeds.rb instead.
Think the above will be failing because your car is not saving, I'm guessing you have some validation in your Car model.
Upvotes: 3