1

Assuming I have a view in my CouchDB named "user/all" and a CouchRest ExtendedDocument as follows:

class User < CouchRest::ExtendedDocument

    property :username
    property :password
    property :realname
    property :role
    property :rights

end

How would I go about retrieving a document for the key 'admin' from this view using this ExtendedDocument?

(If I need to make changes to the ExtendedDocument subclass, what should be changed?)

Many thanks.

Leynos
  • 549
  • 5
  • 10

1 Answers1

1

Try this:

class User < CouchRest::ExtendedDocument

  property :username
  property :password
  property :realname
  property :role
  property :rights

  view_by :role 

end

Here, I am assuming 'admin' is a role property. This will make a view in your design document keyed by role. Then, to get all 'admin' documents, you just do the following:

@admins = User.by_role(:key => 'admin')

If in fact the actual id of the document is 'admin', then all you have to do is this:

@admin = User.get('admin') 

Or, alternatively:

@admin = User.all(:key => 'admin')

I would also suggest taking a look at CouchRest Model, which is basically an Active Model complaint extension to CouchRest if you are using this with Rails. Good Luck!

James
  • 220
  • 2
  • 11
  • Thanks. It seems my problem was that I was approaching this with a view to designing a database schema in futon, then accessing it using the CouchRest extended document class. This is of course completely back to front. I've got it working now by following your example (and using .create! to first store an object in the database). – Leynos Feb 04 '11 at 03:45
  • You can do it that way if you prefer. You just have to call view on the CouchRest database like so... doc = DB.view 'foo/by_role' or whatever. Writing off the top of my head. I just do it in th model there how I have described. You can also explicitly set the map and reduce functions like so... view_by :role, :map => "Your Map Function Here", :reduce => "Reduce Here" – James Feb 04 '11 at 04:16