迁移时无法将数据插入数据库?
我正在使用Rails 3。我不知道是否是rails的规则,在迁移中,似乎我无法将数据插入数据库表。如果有人可以证实确实如此。
我尝试了以下操作:
我有两个 ActiveRecord 模型:
class Car < ActiveRecord::Base
has_many :users
...
end
class User < ActiveRecord::Base
belongs_to :car
...
end
我已经生成了一个迁移文件,在迁移中我有:
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
当我尝试将 default_car 保存到数据库时,我得到 false,并且我的 default_user 有 <强>空 car_id。
是不是因为迁移时不允许将数据存入数据库?
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在迁移中创建数据,但最好不要这样做,而是使用 seeds.rb。
认为上述操作会失败,因为您的汽车没有保存,我猜您对汽车模型进行了一些验证。
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.
好的,我们已经发现存在一些验证问题。所以您现在希望可以跳过验证:
Ok, we've figgured out that there was some validation issues. So you would like to now, that you can skip validations: