Rails 3: API PUT request fails, record not updated

你。 提交于 2019-12-23 01:44:04

问题


I have an application with an API to update artists and a client that tries to interact with the API to update an artist. The problem is that whenever I try to do a PUT request, the record is not updated and the request fails with a Completed 204 No Content in 14ms (ActiveRecord: 0.0ms) error.

Here is the API controller:

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

The method that makes the API call from the client model:

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

And the server logs (API side):

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)

What am I doing wrong?


回答1:


The 204 problem is occurring because update_attributes does not return the model instance. You want your update method to be:

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



回答2:


update_attributes returns either trueor false depending on the success of the operation.

You pass this result to respond_with, so i think this is why you get a 204 code ("no content") - the request is considered successfull whatever the result of update_attributes, but returns no content.




回答3:


The two answers submitted are valid but the core of the problem was that I had validation errors, so the model object was not getting updated...



来源:https://stackoverflow.com/questions/14664866/rails-3-api-put-request-fails-record-not-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!