从 Rails 控制台修改数据库 ID? [英] Modifying Database IDs from Rails Console?

查看:36
本文介绍了从 Rails 控制台修改数据库 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型数据库,并且一直在通过 Rails 页面添加条目.我销毁"了其中一个条目,现在我的 ID 序列跳过了一个.例如,我现在有 42 然后是 44,而不是显而易见的:42、43、44.

I have a small database and have been adding entries through a Rails page. I "destroyed" one of the entries and now my sequence of IDs are skipping by one. For example, I now have 42 then 44, instead of the obvious: 42, 43, 44.

我想知道是否有办法通过控制台编辑新对象的 ID 号.我试过了:

I was wondering if there was a way to edit the ID number of a new object through the console. I have tried:

record.id = 43
record.save

record = record.new
record.attributes = { :id => 43 }

但两者都不起作用.我相当肯定必须有一个控制台方法,但我似乎无法在 Google 上找到太多具体内容,而且我可能错误地阅读了 Rails API……我是否可能必须通过 sqlite 中的直接 SQL 来执行此操作?

but both didn't work. I'm fairly certain there has to be a console method for this, but I can't seem to find much specific on Google and I probably read the Rails API incorrectly... Would I possibly have to do this through direct SQL in sqlite?

谢谢

推荐答案

我可能必须通过 SQLite 中的直接 SQL 来做到这一点吗?

Would I possibly have to do this through direct SQL in sqlite?

是的.

ActiveRecord 的全部意义在于抽象 DB 函数并只返回数据集合.您不应该担心记录的 ID,这是特定于数据库的.我想不出有什么理由引用模特的 ID.

The whole point of ActiveRecord is that is abstracts DB functions and just returns collections of data. You shouldn't be worrying about the ID of a record, that is something specific to the DB. Off the top of my head I can't think of any reasons to reference the model's ID.

如果您的应用程序依赖于一个序列号,那么您应该向具有此序列号的模型添加另一个字段.例如,如果我有一家产品商店(产品型号),并且我将数据库提供给其他供应商的 ID 号提供给其他供应商.两周后,我的老板要求我为两种产品变体提供一个独特但相似的 ID:45a"和45b".坚果.ID 字段应该只用于数据库和 ActiveRecord,而不是您或您的用户来识别记录.

If your app depends on having a sequenced number then you should add another field to the model which has this. For instance, if I have a store with products (a Product model) and I give the ID number the DB provides to other vendors. Two weeks later, my boss asks me to have a unique, but similar ID for two variations of products: "45a" and "45b". Nuts. The ID field should only be used by to the database and ActiveRecord, not you or your users, to identify the record.

可能有一个模糊的方法,如果数据库允许,它会强制设置 ID,但由于某种原因,它是模糊的.不要试图找到它:)

There is a small chance that there might be an obscure method which force sets the ID if the DB allows it, but it is obscure for a reason. Don't try and find it :)

说了这么多,输入ruby script/dbconsole即可快速调出sqlite界面,而无需输入密码.

All that being said, type ruby script/dbconsole to quickly pull up the sqlite interface without having to type your password.

此外,如果您删除了会重置计数器并从 0 开始的 sqlite 数据库.能力越大,责任越大.

Also, if you delete the sqlite database that will reset the counter and start at 0. With great power comes great responsibility.

编辑

如果我没记错的话,戴夫·托马斯在某处写过这件事.也许这里?

If I remember correctly Dave Thomas wrote about this somewhere. Perhaps here?

这篇关于从 Rails 控制台修改数据库 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆