【问题标题】:Rails 3: API PUT request fails, record not updatedRails 3:API PUT 请求失败,记录未更新
【发布时间】:2013-01-17 20:40:24
【问题描述】:

我有一个使用 API 更新艺术家的应用程序和一个尝试与 API 交互以更新艺术家的客户端。问题是每当我尝试执行 PUT 请求时,记录都不会更新,并且请求失败并出现 Completed 204 No Content in 14ms (ActiveRecord: 0.0ms) 错误。

这里是 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)

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails api put


    【解决方案1】:

    提交的两个答案都是有效的,但问题的核心是我有验证错误,所以模型对象没有得到更新......

    【讨论】:

      【解决方案2】:

      update_attributes 根据操作的成功返回 truefalse

      你将此结果传递给respond_with,所以我认为这就是为什么你得到一个 204 代码(“无内容”) - 无论update_attributes 的结果如何,请求都被认为是成功的,但不返回任何内容。

      【讨论】:

        【解决方案3】:

        出现 204 问题是因为 update_attributes 没有返回模型实例。你希望你的更新方法是:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-23
          • 1970-01-01
          • 2019-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-08
          相关资源
          最近更新 更多