在 Mongoid 中重新生成密钥?
目前正在尝试 Mongoid,我遇到了一个可能非常简单但让我不知所措的问题:
我有一个非常简单的文章模型:
class Article
include Mongoid::Document
field :title, :type => String
field :content, :type => String
key :title
referenced_in :subject
validates_presence_of :title
end
我在已经添加了 key :title
之后创建了一条测试记录。新创建的记录按预期工作,但第一篇文章(最初具有正常的 mongoid 对象 id)表现得很奇怪:
在 Rails 视图中,第一篇文章仍然返回其对象 id,而不是新密钥。即使用 link_toarticle.name,article
返回:
<a href="/articles/4ef150970a68b38415000003">Show</a>
...当其余所有返回参数化键时,例如:
<a href="/articles/other-article">Show</a>
如果我单击该链接,我会收到“未找到记录”。我尝试在控制台中加载并重新保存此记录,之后对该记录调用 article.id
确实返回了参数化密钥,但它仍然以旧方式显示在视图中并且不起作用。
那么,有几个问题:
- 这里发生了什么?
- 你如何解决它?
- 这种情况向我表明,如果您将 mongoid 模型上的字段设置为键,您需要真正确保它永远不会改变。那么,当这些偶尔需要更改时,您如何处理像使用文章标题作为标题这样的事情呢?
谢谢!
Just trying out Mongoid at the moment, I've run into an issue that's probably pretty simple but has me at a loss:
I have a really simple Article model:
class Article
include Mongoid::Document
field :title, :type => String
field :content, :type => String
key :title
referenced_in :subject
validates_presence_of :title
end
I added key :title
after I had already created one test record. Newly created records work as expected, but the first Article (which originally had the normal mongoid object id) behaves strangely:
In rails views this first article still returns its object id instead of the new key. ie using link_to article.name, article
returns:
<a href="/articles/4ef150970a68b38415000003">Show</a>
... when all the rest return the parameterized keys, like:
<a href="/articles/other-article">Show</a>
If I click that link I get "Record not found". I tried loading and resaving this record in the console, and after that calling article.id
on that record did return the parameterized key, but it still shows up the old way in the view and doesn't work.
So, a couple questions:
- What's going on here?
- How do you fix it?
- This situation indicates to me that if you set a field on a mongoid model to be the key, you need to be really sure that it will never change. How do you handle something like using the title of an article as a slug, then, when those may occasionally need change?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,由于
_id
是不可变的,您唯一的选择就是使用新的“缓慢”id 重新插入此文档并删除旧的。是的,_id 格式和分片键(如果您使用分片)是您最好从一开始就拥有的两件事:-)
其他一切都可以相对容易地修复。
Well, since
_id
is immutable, your only option is to reinsert this document with your new 'sluggish' id and delete the old one.And yes, _id format and shard key (if you use sharding) are the two things you better have right from the beginning :-)
Everything else can be fixed relatively easily.