Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Jbuilder work with Rails 5 API Mode

I want to use Jbuilder with Rails 5.0.0.beta1.1 in API mode. Out of the box, it doesn't work, even when creating the app/views directory.

For example, I have:

# app/controllers/tests_controller.rb
class TestsController < ApplicationController
  # The requests gets inside the action
  def test
  end
end

# app/views/tests/test.json.jbuilder
json.test "It works!"

The error I'm getting is

No template found for TestsController#test, rendering head :no_content

I guess I have to change some things in the config files. What do I have to do?

like image 880
sauronnikko Avatar asked Jan 28 '16 17:01

sauronnikko


People also ask

How does Jbuilder work?

Jbuilder provides a DSL for generating JSON. It includes a template engine which allows you to create complex responses with helpers and conditions. If you look at the gemfile for a Rails 3.2 application you'll see a see a gem mentioned in the comments that wasn't there in earlier versions called JBuilder.

What is JSON Jbuilder?

Jbuilder gives you a simple DSL for declaring JSON structures that beats manipulating giant hash structures. This is particularly helpful when the generation process is fraught with conditionals and loops. Here's a simple example: # app/views/messages/show.json.jbuilder json.

What is Rails Jbuilder?

Jbuilder is a gem that's maintained by the Rails team and included in the default Rails Gemfile . It's similar to Builder but is used to generate JSON, instead of XML. If you don't have it, you can add the following to your Gemfile : gem 'jbuilder' Copy.

Why use Jbuilder?

Jbuilder is quite useful when it comes to generating and rendering JSON responses for API requests in Rails. This article helps understand, how to render JSON responses in general. Jbuilder is particularly good at following things: Reusable JSON API responses through partials.


1 Answers

Doing an explicit render from the controller like this works:

render 'controller_name/action.json.jbuilder'
like image 163
Dan Sandberg Avatar answered Sep 22 '22 18:09

Dan Sandberg