2010-11-12 19 views
2

我創建了一個簡單的api,該響應使用json。當我嘗試從瀏覽器中調用它時,我得到了相應的json響應,但是當我嘗試從actionscript遠程調用它時,似乎它會像調用方法那樣調用json。這是控制器的動作:Rails respond_with輸出json並試圖將其稱爲方法

def matcher 
    @conn = Connection.first 
    if(@conn) 
     respond_with({:conn => @conn, :status => :ok}.to_json) 
    else 
     respond_with({:status => :no_content}.to_json) 
    end 
    end 

這是當它得到

Started POST "/connection/matcher/1.json" for 127.0.0.1 at 2010-11-11 22:57:24 -0800 
    Processing by ConnectionsController#matcher as JSON 
    Parameters: {"stratus_string"=>"bad1de003755eaa01a2920f0091d0dd66beaf2d34f651b09a578afb1b54e5686", "user_id"=>"1", "id"=>"1"} 
    Connection Load (0.5ms) SELECT "connections".* FROM "connections" LIMIT 1 
Completed in 24ms 

NoMethodError (undefined method `{"conn":{"created_at":"2010-11-12T06:55:13Z","id":6,"stratus_string":"474735730abe81d7622d377bd0bf816c3f94721ece3eddf670bf3a74b1c2356c","updated_at":"2010-11-12T06:55:13Z","user_id":1},"status":"ok"}_url' for #<ConnectionsController:0x000001030e4350>): 
    app/controllers/connections_controller.rb:7:in `matcher' 

爲什麼軌試圖執行JSON響應呼叫服務器的響應?我不明白。

UPDATE:

這裏是ActionScript代碼,使通話,雖然我不明白爲什麼它的確與衆不同。

 this.restService = new HTTPService(); 
     this.restService.url = "http://localhost:3000/connection/matcher/1.json"; 
     this.restService.method = "POST"; 

     this.restService.addEventListener("result", onRestResult); 
     this.restService.addEventListener("fault", onRestFault); 

     var request:Object = new Object(); 
     request.user_id = user; 
     request.stratus_string = id; 
     this.restService.cancel(); 
     this.restService.send(request); 

謝謝!

+0

你能不能發佈你的js代碼? – Sergey 2010-11-12 08:52:39

+0

我沒有js代碼。調用者在動作 – Danny 2010-11-12 09:15:31

+0

更新:它只發生在POST沒有GET – Danny 2010-11-12 15:10:21

回答

5

我很好奇它爲什麼在瀏覽器中有效。我預計它也會在那裏失敗。 檢查源的respond_with:

def respond_with(*resources, &block) 
    raise "In order to use respond_with, first you need to declare the formats your " << 
     "controller responds to in the class level" if self.class.mimes_for_respond_to.empty? 

    if response = retrieve_response_from_mimes(&block) 
    options = resources.extract_options! 
    options.merge!(:default_response => response) 
    (options.delete(:responder) || self.class.responder).call(self, resources, options) 
    end 
end 

這是顯而易見的,爲什麼它會嘗試使用它作爲一種方法。 我猜你應該堅信:

respond_to do |format| 
    format.html # some.html.erb 
    format.json { render :json => {:conn => @conn, :status => :ok}.to_json } 
end 
2

respond_with是一個響應者需要一個對象作爲參數,而不是JSON。它根據該行爲確定適當的響應。

http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering

如果你想使自己的JSON,您使用的respond_to。

+0

上面的鏈接現在已經死亡。 [這裏](https://github.com/rwdaigle/edgerails/blob/master/source/_posts/2009-8-10-what-s-new-in-edge-rails-default-restful-rendering.textile)是github上的文章歸檔。 – 2016-08-11 09:02:23