2011-05-05 43 views
0

iOS的新手。我有一个使用脚手架创建的Post模型的Rails博客应用程序。它有一个名称:字符串和图像。我正在使用ASIHTTPRequest创建一个新帖子。它连接到服务器正常,但参数“名称”和“图像”没有正确传递到数据库中。这里的iphone代码:如何从ASIHTTPRequest发送POST请求到插入DB的Rails

NSURL *url=[[NSURL alloc] initWithString:@"http://localhost:3000/posts"]; 
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 
    [request setPostValue:@"Ben" forKey:@"name"]; 
    [request setFile:@"/Users/Seb/Desktop/beach.jpeg" forKey:@"image"]; 
    [request startSynchronous];  

这里是Rails服务器日志显示:

Started POST "/posts" for 127.0.0.1 at Wed May 04 15:41:43 -0700 2011 
    Processing by PostsController#create as HTML 
    Parameters: {"name"=>"Ben", "image"=>#<ActionDispatch::Http::UploadedFile:0x103eb33a0 @content_type="image/jpeg", @original_filename="beach.jpeg", @headers="Content-Disposition: form-data; name=\"image\"; filename=\"beach.jpeg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#<File:/var/folders/PI/PI+kcHrCHfuDh-K+ppxAxE+++TI/-Tmp-/RackMultipart20110504-11613-zvv5im-0>>} 
MONGODB blog_development['posts'].insert([{"_id"=>BSON::ObjectId('4dc1d627be2eec2d5d00000f')}]) 
Redirected to http://localhost:3000/posts/4dc1d627be2eec2d5d00000f 
Completed 302 Found in 5ms 

正如你所看到的,名字和形象没有得到插入到数据库。当我这样做后从浏览器,服务器日志显示:

Started POST "/posts" for 127.0.0.1 at Mon May 02 00:54:52 -0700 2011 
    Processing by PostsController#create as HTML 
    Parameters: {"commit"=>"Create Post", "post"=>{"name"=>"tiny face", "image"=>#<ActionDispatch::Http::UploadedFile:0x1042b2bb8 @content_type="image/png", @original_filename="Screen shot 2011-05-01 at 11.23.23 PM.png", @headers="Content-Disposition: form-data; name=\"post[image]\"; filename=\"Screen shot 2011-05-01 at 11.23.23 PM.png\"\r\nContent-Type: image/png\r\n", @tempfile=#<File:/var/folders/PI/PI+kcHrCHfuDh-K+ppxAxE+++TI/-Tmp-/RackMultipart20110502-11613-u7czau-0>>}, "authenticity_token"=>"i+4h+XOOuJyTnF+quru8yrBuM1ixlDXC5udYaB/0jP4=", "utf8"=>"✓"} 
MONGODB blog_development['posts'].insert([{"name"=>"tiny face", "image_filename"=>"screen_shot_2011-05-01_at_11.23.23_pm.png", "_id"=>BSON::ObjectId('4dbe634dbe2eec2d5d000002')}]) 
Redirected to http://localhost:3000/posts/4dbe634dbe2eec2d5d000002 
Completed 302 Found in 518ms 

任何想法如何构建我的职务,以使其保存到数据库?

+0

与MongoDB无关 – 2011-05-05 09:23:53

回答

1

您将要发布的表的名称放在括号内的键名前。发布到Rails应用时,我遇到了同样的问题。

[request setPostValue:@"Ben" forKey:@"table [name]"]; 
[request setFile:@"/Users/Seb/Desktop/beach.jpeg" forKey:@"table [image]"]; 
+0

一旦你这样做了,你会得到这样的错误吗? BSON :: InvalidDocument(无法将类ActionDispatch :: Http :: UploadedFile的对象序列化为BSON。): app/controllers/posts_controller.rb:47:在'create' app/controllers/posts_controller.rb:46 :在'创建' – John 2011-05-05 21:38:53

+1

它可能不是我从工作岗位发布的确切代码,但我会检查何时回家并查看我使用的代码。 – 2011-05-06 09:14:00

+0

更正:括号内应该是围绕字段名称而不是表名 – 2011-05-08 18:19:30