EzDevInfo.com

couchrest

A minimalist CouchDB client in ruby CouchRest - Google Groups

Couchdb bad_utf8_character_code

I am using couchdb through couchrest in a ruby on rails application. When I try to use futon it alerts with a message box saying bad_utf8_character_code. If I try to access records from rails console using Model.all it raises either of 500:internal server error, RestClient::ServerBrokeConnection: Server broke connection: or Errno::ECONNREFUSED: Connection refused - connect(2) Could any one help me to sort this issue?


Source: (StackOverflow)

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

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.


Source: (StackOverflow)

Advertisements

Tracking which user edited a CouchDB document

I'm using couchrest_model to interact with CouchDB from ruby. I have a bunch of documents in a database, each of which I've added a key "updated_by" to, which I want to keep information about the user who made the changes that generated that revision.

Is this the right way to do things?

If this is the right way, how should I use couchrest_model so that I can make requests of user data as well as my main database?

Thanks!


Source: (StackOverflow)

Updating CouchDB from Ruby Script

I am having a problem modelling my script. My goal is to have a script that will create a database (if one does not exist) and then update it with a new data after a certain period. Here is what I have so far:

@db = CouchRest.database('http://myurl.com')
$my_database = @db.save_doc(my_hash)
doc = @db.get($my_database['id'])
@db.save_doc(doc)
sleep 300
@db.save_doc(doc)
...

This works fine for creating the database and updating. My problem is that I am having a hard time modelling this script so every time it runs, it does not create a new database but rather appends the already created database. I am very new to ruby and database design, so any insight would be much appreciated!


Source: (StackOverflow)

Object Not Persisting in CouchDB

I am trying to store my ruby object in couchdb with couchrest. I am extending my model from CouchRest::Model::Base But still i am unable to see the changes in db.

I've defined Server as CouchRest.new also mentioned in model to use_database 'players'

# Controller Method
get '/new/:name' do 
    DB = SERVER.database!('players')
    @new_player = Player.new(params['name'])
    @new_player.create
    "success: #{@new_player.persisted?}" #shows true

# Model
class Player < CouchRest::Model::Base
    use_database 'players'
    property :name ,String
    timestamps!

    def initialize(arg)
        @name=arg
    end
end
  • How To Persist the object?
  • How can i retreive all persisted objects?
  • Is there any simple applications which i can refer to?

Source: (StackOverflow)

How to access CouchDB documents using CouchRest model

Please help me to solve this. I’ve around 1500 documents in my CouchDB, each document belongs to any one of the types (‘Survey’ and ’Response’).

I need solution for followings

1] Need to display Document Ids (_id) in a Dropdown list which has document type (documentType) as ‘Survey’

2] If I select an item (_id) from drop down, I need to display all document Ids (_id) in list box which belongs to selected ID (_id selected from drop down list)

I've total 1500 documents like this

{
   "_id": "ff2fb2554682ba613c2f83c63502808a",
   "_rev": "4-dd559696434a402739e789ccc8c9a481",
   "answers": [
       {
           "answers": [
               "Aug 19,2011"
           ],
           "questionId": "50f3df434ae02ac7fff48c1c2bde83e4"
       },
       {
           "answers": [
               "Bechu Yadav"
           ],
           "questionId": "15504f006e58872fd94871fe0c9d32ad"
       },
       {
           "answers": [
               "35"
           ],
           "questionId": "3c447a2f5cc6ca1985ce2c81463a3c47"
       },
       {
           "answers": [
               "Male"
           ],
           "questionId": "a6df7c25602939554612ef6de762f5b9"
       },
       {
           "questionId": "2f66155965e60094f23f01af531d5af1",
           "subAnswers": [
               {
                   "questionId": "1dae2d86eef846c967254c9e369170ce"
               },
               {
                   "questionId": "40ffeb4d33dab1fe8d2d8b73c02ed13b"
               },
               {
                   "questionId": "2db1e8b6e97d5baa8935b9b31fcc9648"
               },
               {
                   "questionId": "0f8bb9f91ea8085b4ffb839ee8deabb5"
               },
               {
                   "questionId": "22a93ecb72c50ff8899f8b2937776e51"
               },
               {
                   "questionId": "e5106384790c2be745c952c4b867a0ff"
               }
           ]

           "questionId": "492cf9bd41257ea478c5222fbba06616"
       }
   ],
   "createdAt": "2011-08-19T21:05:36.486+0000",
   "createdBy": "user4",
   "documentType": "Response",
   "ipAddress": "42.110.85.67",
    "location": {
       "latitude": 26.8415613,
       "longitude": 75.8222883,
       "provider": "network"
   },
    "surveyId": "6df022f0f371752167ad4920b38e1c37",
    "published": true
}

And my CouchRest model looks like as follows

class Android < CouchRest::Model::Base
    property :description, String
    property :_id, String
    property :_rev, String
    property :documentType, String

    design do
      view :by_documentType,:map =>"function(doc){if (doc.documentType == 'Survey') {emit(doc._id);}}"
      view :by_createdBy
    end
 end

But when I access by_documentType it's returning nil

Android.find_by_documentType('Survey')

Source: (StackOverflow)

Primary Keys and CouchDB

CouchDB's versioning is an absolute boon to the application I'm writing, but each of the objects I want to represent in the database has it's own unique identifier (let's call it my_id), so I don't really need the _id field.

Is there a way for me to tell CouchDB that I want to make my field the primary hey (not _id)?

I'm using ruby's couchrest_model, so I know I can do Model.find_by_my_id(params[:my_id]) if I've put view_by :my_id in my class, but this feels like I'm storing an _id for no purpose. Should I care?


Source: (StackOverflow)

couchrest / open-uri returning empty rows for key in couchdb view

I thought this was a problem with couchrest, but seems to be a deeper internal Ruby problem. With the following couchdb view key/values:

...
{"key":["Document-2458","MethodID","286"],"value":1},
{"key":["Document-2458","MethodID","287"],"value":1},
{"key":["Document-2458","MethodID","288"],"value":1},
{"key":["Document-2458","MethodID","92"],"value":1},
...

If I ask for the view this way:

conn_str = 'http://127.0.0.1:5984/portal_development/_design/all_data_values/_view/view1?group=true'
key = '["Document-2458","MethodID","287"]'
result = JSON.parse(open(conn_str + "&key=" + CGI.escape(key)).read)
puts result

I get this result:

{"rows"=>[{"key"=>["Document-2458", "MethodID", "287"], "value"=>1}]}

But if I do this:

conn_str2 = 'http://127.0.0.1:5984/portal_development/_design/all_data_values/_view/view1?group=true'
key = '["Document-' + "2485" + '","MethodID","287"]'
result = JSON.parse(open(conn_str2 + "&key=" + CGI.escape(key)).read)
puts result

I get an empty result:

{"rows"=>[]}

I cannot for the life of me figure out why... I've even resorted to cracking open wireshark and watch both queries on the wire. The bytes in the data portion of the packet are identical (the stuff with the url and params). And I verify that couchdb is indeed sending me back non-empty data for the first, and empty data on the second. Couchdb even shows identical queries in the log:

[info] [<0.19053.0>] 127.0.0.1 - - 'GET' /portal_development/_design/all_data_values/_view/view1?group=true&key=%5B%22Document-2458%22%2C%22MethodID%22%2C%22287%22%5D 200
[info] [<0.19055.0>] 127.0.0.1 - - 'GET' /portal_development/_design/all_data_values/_view/view1?group=true&key=%5B%22Document-2485%22%2C%22MethodID%22%2C%22287%22%5D 200

The problem is whenever I concat the string instead of hard coding it, even thought the resulting string are the same. But I have no idea why. Thoughts?


Source: (StackOverflow)

Difference betwee destroy and delete_doc in couchrest

I've been trying to delete docs in couchdb (using ruby couchrest) to recover disk space. I realize that deleting docs may not free up space. I then used Document::destroy (it sounded like it would work). After compacting views it seemed like it freed up much more than it should.

Can you explain what destroy does? Do you know why I recovered so much space?


Source: (StackOverflow)

Is it possible to access lists using CouchRest?

I am looking for a way to access a list I have defined as part of a couchdb design document whilst using CouchRest.

I have tried changing the call from being something like;

CouchRest.database("http://mycouchdb.com/db").view("interactions/myview")

To

CouchRest.database("http://mycouchdb.com/db").view("interactions/_list/mylist/myview")

But I get a parse error, and there doesn't appear to be a function like .view or any parameters I can set to tell it which list to use.

Any help would be greatly appreciated.


Source: (StackOverflow)

How can I replay a header which is sent in request to couch db?

How can I replay a header which is sent as request to couch db, catch is I want to do it for all documents of data base irrespective of show functions.

So I would send a request to couch db for creating a document as

 curl -X POST -i -H "Content-Type: application/json" -H "User-Agent: CURL" --data-binary          @${INPUTFILE}  http://someip:port/db

where db is my database name created already in couch db and input file is json file to be sent to couch db which will be stored.

Here the response is always as follows

HTTP/1.1 201 Created
Server: CouchDB/1.5.0 (Erlang OTP/R16B01)
Location: http://someip:port/db/14f49d6e537268402761d873560b1da9^M
ETag: "1-ad9ad86f3ca9b8671cd0fcb9e546971f"
Date: Mon, 10 Mar 2014 19:41:07 GMT^M
Content-Type: text/plain; charset=utf-8
Content-Length: 95
Cache-Control: must-revalidate^M

{"ok":true,"id":"14f49d6e537268402761d873560b1da9","rev":"1-ad9ad86f3ca9b8671cd0fcb9e546971f"}

Now I need get an additional header in the response. I know we can easily do this by showfunctions, but the catch there is I have to send post request to a url of that show function similar to as follows

http://someip:port/db/_design/mydesigndoc/_show/myshowfunction

But I don't want this, I want to know whether it would be possible to just post to http://someip:port/db/ and get a custom response header back?

Or is there a way where I can front end the address to http://someip:port/db and forward it to http://someip:port/db/_design/mydesigndoc/_show/myshowfunction when ever I receive a request? I guess this should be possible, but couldn't figure out.

Any help would be greatly appreciated. Thanks


Source: (StackOverflow)

Testing errors in Rails with CouchRest Model using RSpec

I have a normal Rails project (without Active Record) using CouchDB (couchrest_model) as a document database.

I did setup RSpec and a basic scaffold 'Project'.

When I test the following spec:

  before(:each) do
    @project = Project.create! valid_attributes
  end

  describe "GET index" do
    it "assigns all projects as @projects" do
      get :index
      assigns(:projects).should eq([@project])
    end
  end

I get the following error:

Failure/Error: assigns(:projects).should eq([@project])

       expected [{"name"=>"test", 
                  "updated_at"=>2011-05-28 11:24:04 -0500,
                  "created_at"=>2011-05-28 11:24:04 -0500, 
                  "couchrest-type"=>"Project",
                  "_id"=>"709edbfaafb24fa1eff7d5f3966b2bda",
                  "_rev"=>"1-ae3f6356f8e32f6006337a4f3759bca4"}]
            got [{"name"=>"test",
                  "updated_at"=>2011-05-28 11:24:04 -0500, 
                  "created_at"=>2011-05-28 11:24:04 -0500,
                  "_id"=>"709edbfaafb24fa1eff7d5f3966b2bda",
                  "_rev"=>"1-ae3f6356f8e32f6006337a4f3759bca4",
                  "couchrest-type"=>"Project"}]

It seems that the only difference is the order of the elements in the hash:

  (compared using ==)

   Diff:

   @@ -1,7 +1,7 @@
    [{"name"=>"test",
      "updated_at"=>2011-05-28 11:24:04 -0500,
      "created_at"=>2011-05-28 11:24:04 -0500,
   -  "couchrest-type"=>"Project",
      "_id"=>"709edbfaafb24fa1eff7d5f3966b2bda",
   -  "_rev"=>"1-ae3f6356f8e32f6006337a4f3759bca4"}]
   +  "_rev"=>"1-ae3f6356f8e32f6006337a4f3759bca4",
   +  "couchrest-type"=>"Project"}]

I know 'rspec' and 'rspec-rails' only work out of the box for Active Record, but it shouldn't be so different for other ORMs. Am I missing something?

Which is the best way to fix this test?


Source: (StackOverflow)

how to use rails-api gem with CouchRest model

I'm trying to set up a rails API using the rails-api gem rails-api and couchrest model. Using rails-api strips out a lot of the middleware and modules and I believe that is why I'm getting the following error:

Started GET "/assets" for 127.0.0.1 at 2012-10-10 16:00:36 +0100
Connecting to database specified by database.yml

ActiveRecord::ConnectionNotEstablished (ActiveRecord::ConnectionNotEstablished):
activerecord (3.2.8) lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
activerecord (3.2.8) lib/active_record/connection_adapters/abstract/connection_specification.rb:170:in `retrieve_connection'
activerecord (3.2.8) lib/active_record/connection_adapters/abstract/connection_specification.rb:144:in `connection'
activerecord (3.2.8) lib/active_record/query_cache.rb:67:in `rescue in call'
activerecord (3.2.8) lib/active_record/query_cache.rb:61:in `call'
activerecord (3.2.8) lib/active_record/connection_adapters/abstract/connection_pool.rb:473:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `_run__2405051170962911444__call__2117088860059348020__callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.8) lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.8) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/reloader.rb:65:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
railties (3.2.8) lib/rails/rack/logger.rb:26:in `call_app'
railties (3.2.8) lib/rails/rack/logger.rb:16:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/request_id.rb:22:in `call'
rack (1.4.1) lib/rack/runtime.rb:17:in `call'
activesupport (3.2.8) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.4.1) lib/rack/lock.rb:15:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/static.rb:62:in `call'
railties (3.2.8) lib/rails/engine.rb:479:in `call'
railties (3.2.8) lib/rails/application.rb:223:in `call'
rack (1.4.1) lib/rack/content_length.rb:14:in `call'
railties (3.2.8) lib/rails/rack/log_tailer.rb:17:in `call'
rack (1.4.1) lib/rack/handler/webrick.rb:59:in `service'
/Users/jason/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
/Users/jason/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
/Users/jason/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'


Rendered /Users/jason/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.9ms)
Rendered /Users/jason/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.9ms)
Rendered /Users/jason/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.1ms)

Can anyone point out what modules and middleware I would need to include to get it working? Thanks


Source: (StackOverflow)

How to add property in module in Rails CouchRest Model to support multiple inheritance?

In my class, I want to include multiple modules. Each module can define its own property to persist in couchDB.

Here is an example:

module Owner
 property :name
end

module Animal
 property :type
end

class Cat
 include Owner
 include Animal
end

This doesn't work. I got this error: "undefined method `property'". I tried added CouchRest::Model::Embeddable but it won't work for module either. All the examples I am seeing are extending from CouchRest::Model::Base. However, I won't be able to use this approach because Ruby doesn't support multiple inheritance.

I won't be able to change the underlying JSON format. My desired format is {"name":"tom","type":"cat"}.

Any help would be appreciated. Thanks!


Source: (StackOverflow)

How to use CouchRest with Sunspot?

I have a problem with integration between CouchRest and Sunspot. When I search the book detail, the result from Sunspot is empty. I try to google it for a long time but no help.

Started GET "/books/search?utf8=%E2%9C%93&query=Book of Life&commit=Search%21" for 127.0.0.1 at 2011-09-08 11:27:41 +0700
Processing by BooksController#search as HTML
Parameters: {"utf8"=>"?", "query"=>"Book of Life", "commit"=>"Search!"}
Rendered books/index.html.erb within layouts/application (10.7ms)
Completed 200 OK in 145ms (Views: 20.6ms | ActiveRecord: 0.0ms)
[] <-- I got empty result

My System

  • Ruby 1.9.2p290
  • Rails 3.0.10
  • CouchDB 1.1.0

File structure ( https://gist.github.com/1164637/ )

  • Model (/app/models/book_detail.rb)
  • Controller (/app/controllers/books_controller.rb)
  • Sunspot Adapter for CouchRest (/config/initializers/couchdb.rb)
  • Sunspot Adapter Module (/config/initializers/sunspot_couch.rb)

NOTE: Sorry about code link. I always got "Please indent all code by 4 spaces using the code toolbar button". I try to remove all tab and follow SO code formatting guideline but it not work anymore.


Source: (StackOverflow)