2013-02-02 67 views
1

我有一個應用程序使用API​​更新藝術家以及嘗試與API交互以更新藝術家的客戶端。問題是,每當我嘗試執行PUT請求時,記錄都不會更新,並且請求失敗,並顯示Completed 204 No Content in 14ms (ActiveRecord: 0.0ms)錯誤。Rails 3:API PUT請求失敗,記錄未更新

這裏是API控制器:

class Api::V1::ArtistsController < Api::V1::BaseController 
    respond_to :json 

    def show 
    respond_with Artist.find_by_id(params[:id]) 
    end 

    def update 
    artist = Artist.find_by_id(params[:id]) 
    respond_with artist.update_attributes(params[:artist]) 
    end 
end 

,使得從客戶機模型的API調用的方法:

def update_artist_attributes 
    self.class.put("/api/artists/#{self.artist_id}.json", { body: { 
    artist: { 
     bio: self.artist_attributes_copy[:bio], 
     phone_number: self.artist_attributes_copy[:phone_number], 
     country: self.artist_attributes_copy[:country], 
     city: self.artist_attributes_copy[:city] 
    } 
    } }) 
end 

而服務器日誌(API側):

Started PUT "/api/artists/1.json" for 127.0.0.1 at 2013-02-02 19:00:00 +0100 
Processing by Api::V1::ArtistsController#update as JSON 
    Parameters: {"artist"=>{"bio"=>"NERVO sisters are not lesbians and they're hot! And they're single too!", "phone_number"=>"218391", "country"=>"Afghanistan", "city"=>"dnajksakd"}, "id"=>"1"} 
    Artist Load (0.4ms) SELECT "artists".* FROM "artists" WHERE "artists"."id" = 1 LIMIT 1 
    (0.2ms) BEGIN 
    Artist Exists (0.4ms) SELECT 1 AS one FROM "artists" WHERE "artists"."access_token" = 'EqHG8SGh9ldl3W-U5PBECw' LIMIT 1 
    Artist Exists (0.6ms) SELECT 1 AS one FROM "artists" WHERE (LOWER("artists"."access_token") = LOWER('EqHG8SGh9ldl3W-U5PBECw') AND "artists"."id" != 1) LIMIT 1 
    Artist Exists (0.5ms) SELECT 1 AS one FROM "artists" WHERE ("artists"."email" IS NULL AND "artists"."id" != 1) LIMIT 1 
    (0.3ms) ROLLBACK 
Completed 204 No Content in 14ms (ActiveRecord: 0.0ms) 

我做錯了什麼?

回答

4

發生了204問題,因爲update_attributes未返回模型實例。您希望您的更新方法是:

artist = Artist.find_by_id(params[:id]) 
artist.update_attributes(params[:artist]) 
respond_with artist 
1

update_attributes返回或者truefalse取決於手術的成功。

傳遞給這個結果respond_with,所以我想這就是爲什麼你會得到一個204碼(「沒有內容」) - 該請求被認爲是全成的update_attributes無論結果如何,但不返回任何內容。

0

提交的兩個答案都是有效的,但問題的核心是我有驗證錯誤,所以模型對象沒有得到更新...