2012-10-09 44 views
3

在XCode(iOS)中,我使用JSON訪問rails數據庫。我已經創建了特定的操作來從數據庫檢索數據並將數據輸入到數據庫中。使用json返回創建的rails項目的id

我想在我的數據庫中插入一條記錄,並立即返回創建的對象的ID。但我找不到將這些操作「鏈接」在一起的方法。

將數據插入,我用這樣的請求:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://..."]]; 
    [request setHTTPMethod:"@POST"]; 
    [request addValue:@"application/json" forHTTPHeaderField:@"content-type"]; 
    NSData *objectData = [NSData alloc]; 
    NSError *parseError = nil; 
    objectData = [NSJSONSerialization dataWithJSONObject:myData options:NSJSONWritingPrettyPrinted error:&parseError]; 
    [request setHTTPBody:objectData]; 

進行數據檢索我使用以下命令:

NSMutableArray *myArray = [[NSMutableArray alloc] init]; 

    NSData *myContent = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://..."]]; 
    NSError *parseError = nil; 
    NSInputStream *myStream = nil; 

    myStream = [[NSInputStream alloc] initWithData:myContent]; 
    [myStream open]; 

    myArray = [NSJSONSerialization JSONObjectWithStream:myStream options:NSJSONReadingAllowFragments error:&parseError]; 

回答

0

我覺得在控制器JSON動作,你可以使用類似

def json 
    #-- do your magic to fill @object -- 
    if @object.save 
    respond_to do |format| 
     format.json { render :json => {:id => @object.id} } # Return the id 
     # format.json { render :json => @object } #You can return the whole object 
     format.html { render :string => "#{@object.inspect}" } 
    end 
    else 
    render :json => {:error => "OMG Failed to save the model!"} 
    end 
end