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!
Well, since
_idis 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.