Strange behavior with response_with syntax for a Rails 3 application?

There is some unexpected behavior when creating the api for the Rails 3.0.3 application that runs json.

Below is the controller. Question about respond_with . I already have respond_to :json in the application controller.

The create action just works, and the data is also sent back after creation.

But the update respond_with does not return any data.

The response body is empty.

 def create line = get_line input_header = line.input_headers.create(params[:input_header]) respond_with(input_header, :location => api_v1_line_input_header_url(line,input_header)) end def show input_header = get_input_header respond_with(input_header.to_json) end def update input_header = get_input_header input_header.update_attributes(params[:input_header]) respond_with(input_header, :location => api_v1_line_input_header_url(input_header.line,input_header)) # render :json => input_header end 

When I use render :json => input_header instead of respond_with , it works. Why is this?

+6
source share
3 answers

Firstly, the show method is not too good, you do not need to call the #to_json method, because respond_with automatically calls the corresponding method when it detects that the request requires json content or xml content.

Secondly, what exactly happens in the get_input_header method? Can you replace it with standard rails InputHeader.find(params[:id]) for one shot?

+1
source

response_with returns the body only for GET and POST requests, otherwise it returns only headers

look at this RoR code

  # This is the common behavior for formats associated with APIs, such as :xml and :json. def api_behavior(error) raise error unless resourceful? if get? display resource elsif post? display resource, :status => :created, :location => api_location else head :no_content end end 

and josevalim respond to this pull request expansion (Make reply_with returns JSON / XML for PUT requests)

In my application, I used monkeypatching for this :(

 elsif put? display resource, status: :ok ... 
+1
source

Perhaps you forgot to add response_to to the controller?

 respond_to :json, :html, ... 
0
source

Source: https://habr.com/ru/post/888530/


All Articles