I wonder if there is a way to use a custom string value (e.g. name of the object) as the 开发者_如何转开发_id field instead of a guid in CouchRest Model.
E.g.
class Cat < CouchRest::Model::Base
property :name
end
By default, it will use a guid as _id field. But I just want to use the name property as _id.
You could try using unique_id as follows
class Cat < CouchRest::Model::Base
property :name
unique_id :name
end
unique_id will call any method before the document is first saved, and assign that as the _id of the document. However you'll then have a Cat documents with both the _id and name fields set. They might even come out of sync if the name is changed.
A possibly better option would be to create a getter and setter which would simply change the _id attribute of the document
class Cat < CouchRest::Model::Base
def name
self['_id']
end
def name=(value)
self['_id']=value
end
end
Seeing as there is no extra property in this case, name will always return the id of the document. However, it won't be possible to change the name once the document is written as reassigning the _id will have no effect.
For more information: Here's the rdoc for unique_id. You can also check out couch rest models' wiki entry for validations
精彩评论