Weird behaviour with respond_with syntax for a Rails 3 app?
While building an api for Rails 3.0.3 app that serves json, some unexpected behaviour is happening.
Following is the controller. The question is about the respond_with
. I already have respond_to :json
in the app controller.
The create action just works and the data is also sent back after creation.
But the update action's respond_with
doesn't send back any data.
The response body is blank.
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 => 开发者_StackOverflowinput_header
instead of respond_with
, it works.
Why is this?
First, the show
method is not too well, you do not need to call #to_json method, because respond_with
is automatically calls the correspondent method when it detects the request needs json content or xml content.
Secondly, what happens exactly in get_input_header
method? Can you replace it with standard rails InputHeader.find(params[:id])
solution for one shot?
respond_with returns body only for GET and POST requests, otherwise it returns only headers
look at this RoR's 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 the josevalim's answer in this pull request's discution (Make respond_with return JSON/XML for PUT requests)
In my app I used monkeypatching for that :(
elsif put?
display resource, status: :ok
...
Maybe you forget append to controller respond_to?
respond_to :json, :html, ...
精彩评论