views:

408

answers:

2

I have a model called Book, which has_many :photos (file attachments handled by paperclip).

I'm currently building a client which will communicate with my Rails app through JSON, using Paul Dix's Typhoeus gem, which uses libcurl.

POSTing a new Book object was easy enough. To create a new book record with the title "Hello There" I could do something as simple as this:

require 'rubygems'
require 'json'
require 'typhoeus'

class Remote
  include Typhoeus
end

p Remote.post("http://localhost:3000/books.json",
  { :params =>
    { :book => { :title => "Hello There" }}})

My problems begin when I attempt to add the photos to this query. Simply POSTing the file attachments through the HTML form creates a query like this:

 Parameters: {"commit"=>"Submit", "action"=>"create", "controller"=>"books", "book"=>{"title"=>"Hello There", "photo_attributes"=>[{"image"=>#<File:/var/folders/1V/1V8Kw+LEHUCKonqJ-dp3oE+++TI/-Tmp-/RackMultipart20090917-3026-i6d6b9-0>}]}}

And so my assumption is I'm looking to recreate the same query in the Remote.post call.

I'm thinking that I'm letting the syntax of the array of hashes within a hash get the best of me. I've been attempting to do variations of what I was expecting would work, which would be something like:

p Remote.post("http://localhost:3000/books.json", 
  { :params => 
    { :book => { :title => "Hello There",
                 :photo_attributes => [{ :image => "/path/to/image/here" }] }}})

But this seems to concatenate into a string what I'm trying to make into a hash, and returns (no matter what I do in the :image => "" hash):

NoMethodError (undefined method `stringify_keys!' for "image/path/to/image/here":String):

But I also don't want to waste too much time figuring out what is wrong with my syntax here if this isn't going to work anyway, so I figured I'd come here.

My question is: Am I on the right track? If I clear up this syntax to post an array of hashes instead of an oddly concatenated string, should that be enough to pass the images into the Book object?

Or am I approaching this wrong?

+1  A: 

Actually, you can't post files over xhr, there a security precaution in javascript that prevents it from handling any files at all. The trick to get around this is to post the file to a hidden iframe, and the iframe does a regular post to the server, avoiding the full page refresh. The technique is detailed in several places, possibly try this one (they are using php, but the principle remains the same, and there is a lengthy discussion which is helpful):

Posting files to a hidden iframe

kaleidomedallion
This is a very interesting point, however this client is not a browser-based application so an iframe is unfortunately out of the question.
Bryan Woods
A: 

What did you end up doing for this issue?

bramswenson