ActiveRecord Rails 3.1 的迁移向下方法截断表
我在迁移时的 up
方法上定义了以下内容来设置初始数据:
def up
Color.create!({:id=>1,:name=>"",:color=>"FF6633"})
Color.create!({:id=>2,:name=>"",:color=>"93B233"})
Color.create!({:id=>3,:name=>"",:color=>"4D90D9"})
Color.create!({:id=>4,:name=>"",:color=>"C43092"})
end
是否有任何 truncate
指令可以放在 down
方法上比如:
def down
Color.truncate
end
或者因为我在创建时设置 ID,所以我应该只使用模型 Color
的 destroy_all
方法吗?
I have the following defined on my up
method on my migration to set initial data:
def up
Color.create!({:id=>1,:name=>"",:color=>"FF6633"})
Color.create!({:id=>2,:name=>"",:color=>"93B233"})
Color.create!({:id=>3,:name=>"",:color=>"4D90D9"})
Color.create!({:id=>4,:name=>"",:color=>"C43092"})
end
Is there any truncate
directive I can put on the down
method like:
def down
Color.truncate
end
Or since I'm setting the IDs on the create should I use only the destroy_all
method of the model Color
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在
up
方法中简单地使用它,这也将解决您的截断和 id 重置问题。干杯!
You can simple use this in your
up
method, this will solve your both truncate and id resetting problem also.Cheers!
首先,您不必将
:id
传递到create!
中,因为 ActiveRecord 会自动处理该问题,因此:id
可能会被忽略(假设标准情况)。其次,在迁移中使用 ActiveRecord 查询生成器并不是一个好的做法,因为如果模型颜色名称发生更改,迁移就会中断。我强烈建议您使用纯 SQL 并使用
execute()
执行该查询。第三,对于
#down
方法,您不应该截断表。您应该销毁在#up
中创建的这 4 种颜色。我会这样写:
Firstly, you don't have to pass
:id
intocreate!
because ActiveRecord will automatically handle that, thus:id
likely to get ignored (standard case assumed).Secondly, it is not a good practice to use ActiveRecord query builder in migration because should the model Color name be changed, you are to have a broken migration. I highly recommend you to use pure SQL and execute that query with
execute()
.Thirdly, for the
#down
method, you shouldn't truncate the table. You should destroy those 4 colors that you created in#up
.Here's how I would write it: