Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails looking for template for JSON requests

In my routes.rb I have:

resources :workouts

In my workouts controller I have:

def show
  respond_to do |format|
    format.html
    format.json { render :json => "Success" }
  end
end

But when I go to /workouts/1.json, I receive the following:

Template is missing

Missing template workouts/show, application/show with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "/home/rails/app/views"

Which appears to show that the format is what it should be but it's still searching for a view. This same code functions in other controllers with identical setups just fine. Also, going to /workouts/1 for the html view seems to work just fine, though it also renders the html view properly when the format.html is removed.

like image 800
makewavesnotwar Avatar asked Nov 15 '13 17:11

makewavesnotwar


1 Answers

Looks at the source code of render

      elsif options.include?(:json)
        json = options[:json]
        json = ActiveSupport::JSON.encode(json) unless json.is_a?(String)
        json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
        response.content_type ||= Mime::JSON
        render_for_text(json, options[:status])

Pay attention to the third line. If the value of :json is a string, render won't call to_json automatically for this value.

So the value remains as string and render will go on to search template.

To fix, supply a valid hash even for trying purpose.

format.json { render :json => {:message => "Success"} }
like image 95
Billy Chan Avatar answered Nov 12 '22 16:11

Billy Chan