开发者

CouchRest Model use a custom value instead of guid for _id field

开发者 https://www.devze.com 2023-04-08 14:20 出处:网络
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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消