Here is a simple Model.
class Event
include Mongoid::Document
field :name, type: String
field :schedule, type: String
field :description, type: String
field :active, type: Boolean, default: true
key :name
end
1.We create and event
ruby-1.9.2-p0 > event = Event.ne开发者_Python百科w(:name => "event1")
=> #<Event _id: event1, _type: nil, _id: "event1", name: "event1", schedule: nil, description: nil, active: true>
ruby-1.9.2-p0 > event.save!
=> true
2.Know lets find the event
ruby-1.9.2-p0 > event = Event.find("event1")
=> #<Event _id: event1, _type: nil, _id: "event1", name: "event1", schedule: nil, description: nil, active: true>
3.So update event attributes
ruby-1.9.2-p0 > event.update_attributes!(:name => "new name")
=> true
4.Lets try to find the event
ruby-1.9.2-p0 > event = Event.find("new name")
Mongoid::Errors::DocumentNotFound: Document not found for class Event with id(s) new name.
5.Ooops not found, but the old one is still persisted
ruby-1.9.2-p0 > event = Event.find("event1")
=> #<Event _id: event1, _type: nil, _id: "event1", name: "event1", schedule: nil, description: nil, active: true>
What I am doing wrong ? I hope this is not a bug. I don't believe MongoDB lets you alter an _id
field. When I try it using the standard mongo shell, I get this error (meaning it's not a Mongoid limitation, it's a limitation in the actual Mongo software):
Mod on _id not allowed
Whenever you need to alter the name
field, you'll probably need to:
- Copy it to a new record with the new name.
- Delete the old record
精彩评论