【发布时间】:2018-04-30 10:58:58
【问题描述】:
以下迁移文件成功运行,没有任何错误,甚至创建了列,但奇怪的是数据没有更新。
如果我在 rails 控制台中运行代码(忽略创建列),它的效果非常好。任何解释:
class AddSubjectListToTestType < ActiveRecord::Migration
def change
add_column :test_types, :subject_list, :integer, array:true, default: []
type_hash = {
"NEET" => ["Physics" , "Chemistry", "Botany", "Zoology"],
"JEE" => ["Physics", "Chemistry", "Mathematics"],
"CET" => ["Physics", "Chemistry", "Mathematics"]
}
TestType.all.each do |test_type|
type_hash[test_type.name].each do |subject|
test_type.subject_list << Subject.find_by_name(subject).id
end
test_type.save
end
end
end
【问题讨论】:
-
它遍历所有
test_types,所以我的第一个问题是你的数据库中有多少这样的?顺便说一句,将迁移与模型结合并不是最佳实践。模型可以改变,迁移不应该。 -
我在测试类型中只有三个记录,并且所有三个记录的名称都列在 question_count_per_subject 的键中。
标签: ruby-on-rails ruby-on-rails-4 database-migration postgresql-9.1