1

Can some one give me an example of using CouchRest to store a standalone attachment in CouchDB?

This is for a non Rails project. So something which does not involve CouchRest::Model would be nice.

thanks, mano

Kelan
  • 2,296
  • 1
  • 15
  • 17
Manokaran K
  • 320
  • 1
  • 2
  • 11
  • I found the answer! I was mucking around with the attachments.rb (in CouchRest source) helper module. The actual method to use is put_attachment in database.rb.... line number 313. – Manokaran K Sep 30 '11 at 10:21

1 Answers1

0

It looks like the CouchRest github UsageOverview wiki page has some basic examples, in the "Attachments" section:

contents = "<html><body>If you're happy and you know it, clap your hands.</body></html>"
@db.put_attachment(doc, "happy.html", contents, :content_type => "text/html")
# => {"ok"=>true, "id"=>"e0d70033da0fad3707fed320bd7e0770", "rev"=>"2-20635570c75e8b20f7a73fd1538f318d"}

# NOTE: The document is not updated automatically with the attachment information
pp doc.to_hash
# {"_id"=>"e0d70033da0fad3707fed320bd7e0770",
#  "_rev"=>"1-cbb61d1f90f7c01b273737702265b6c8",
#  "key"=>"value",
#  "another key"=>"another value"}

# If you try to fetch the attachment without getting the new state of the document, you will fail

@db.fetch_attachment(doc, "happy.html")
# => RestClient::ResourceNotFound: 404 Resource Not Found: {"error":"not_found","reason":"Document is missing attachment"}

doc = @db.get(doc["_id"])

pp doc.to_hash
# {"_id"=>"e0d70033da0fad3707fed320bd7e0770",
#  "_rev"=>"2-20635570c75e8b20f7a73fd1538f318d",
#  "key"=>"value",
#  "another key"=>"another value",
#  "_attachments"=>
#   {"happy.html"=>
#     {"content_type"=>"text/html",
#      "revpos"=>2,
#      "digest"=>"md5-q3MreM1aJgfSLHGrJLdg4g==",
#      "length"=>75,
#      "stub"=>true}}}

@db.fetch_attachment(doc, "happy.html")
=> "<html><body>If you're happy and you know it, clap your hands.</body></html>"

See the rest of the page for more examples (including deleting attachments).

Kelan
  • 2,296
  • 1
  • 15
  • 17