cman77
cman77

Reputation: 1783

Rails4 Jbuilder templates not being found

I am trying to setup a simple JSON response using Jbuilder. My controller is as follows:

class Api::V1::JobsController < Api::V1::BaseController
   def show
      @job = Job.find(params[:id])
   end
end

I have a jbuilder template here:

views\api\v1\jobs\show.json.jbuilder

For some reason when loading the page in a browser or Postman the controller is hit, but the jbuilder template is not found. I get a:

Rendered text template (0.5ms) Completed 404 Not Found in 298ms

If I modify the show action on the jobs controller and add a render json: @job I get the desired output, but of course it isn't using the jbuilder template.

Can't figure out why it isn't seeing the jbuilder template!

added some addition details if I go to the .json url

Started GET "/api/v1/jobs/69407.json" for 127.0.0.1 at 2016-01-21 19:16:44 -0500
Processing by Api::V1::JobsController#show as JSON
  Parameters: {"id"=>"69407"}
  Job Load (18.3ms)  SELECT  "jobs".* FROM "jobs" WHERE "jobs"."id" = $1 LIMIT 1  [["id", 69407]]
  Rendered text template (0.5ms)
Completed 404 Not Found in 86ms (Views: 1.1ms | ActiveRecord: 56.4ms)

update - I have found that if I specifically reference the jbuilder template it loads:

render 'show', formats: [:json], handlers: [:jbuilder], status: 200

Also - in order to even get the above to work, I had to add the jbuilder gem to my gem file - which is odd as I am on Rails 4 which should include it by default?

Upvotes: 2

Views: 1906

Answers (2)

Olalekan Sogunle
Olalekan Sogunle

Reputation: 2357

What I think is that you might have to put a respond_to :json in your application controller or base controller. The default is html and I see a rendered text template.

Upvotes: 2

blnc
blnc

Reputation: 4404

To expand on @OlalekanSogunle's answer. You can set how you want the action to respond in a couple different ways.

In the routes (this will default the actual routes to set the header request to format json):

Rails.application.routes.draw do

    namespace :api do
        namespace :v1 do
            get 'jobs/show', to: 'jobs#show', defaults: { format: :json }, as: :job
        end
    end

end

In the Controller as a class default:

class Api::V1::JobsController < Api::V1::BaseController

   respond_to :json

   def show
      @job = Job.find(params[:id])
   end

end

In the Controller as an action default:

class Api::V1::JobsController < Api::V1::BaseController

   def show
      @job = Job.find(params[:id])

      respond_to do |format|
         format.json
      end
   end

end

Upvotes: 3

Related Questions