Why doesn't response_with return json from my model?

Why doesn’t answer_responses with json in this case? I am invoking an action with explicit .json (/tasks/4e3c1163a19d461203000106/items/4e4c27dfa19d46e0e400000a.json)

In my controller

class Tasks::TasksController < Tasks::BaseController respond_to :html, :js, :json def update @task = @taskgroup.update_task(params[:id], params[:task]) @taskgroup.save respond_with @task end end 

When I flipped to_json and added a breakpoint, it didn’t hit. Answer:

 {} 

If I replaced response_with with an explicit call to_json:

 respond_with @task do |format| format.json { render json: @task.to_json } end 

The answer is perfect:

 { "_id":"4e4c27dfa19d46e0e400000a", "assigned_to":null, "comments" [{"_id":"4e4c2fd7a19d46e127000014", [SNIP] 

In the latter case, it works fine, but I would like to find out why the first does not work. This happens for other controllers and models in my application. Not sure if this is a mangooid thing? (rails 3.0.9 / mongoid 2.1.8)

+7
source share
2 answers

Well see how this happens. When you call respond_with inside the update action, then (if the object is valid), it is redirected to the show action (if you do not want this default behavior, you must provide location: "other_action" before respond_with ).

+1
source

Here is the monkeypatch file I wrote to, always responding with what you tell him, regardless of protocol. Be warned that this violates RESTful best practices, and if you respond with RESTful then it might break. However, if your JSON / XML responses are separate from the main application, then this is useful, and your other controllers will not violate.

Usage, Include this in any controller to override response_with functionality.

 class ApiController < BaseController include ValidResponder end 

Then everything that extends ApiController will include this functionality.

Save the following in app / lib / valid_responder.rb:

 #Override restful responses. module ValidResponder def self.included(base) ActionController::Responder.class_eval do alias :old_api_behavior :api_behavior define_method :api_behavior do |error| if controller.class.ancestors.include?(base) raise error unless resourceful? display resource else old_api_behaviour(error) end end end end end 

For reference, the real source of the method is available here: http://api.rubyonrails.org/classes/ActionController/Responder.html#method-i-api_behavior

+3
source

All Articles