Sig
Sig

Reputation: 5948

Basic usage of Jbuilder in a controller

In a Rails (5.2) app, I'm trying to use JBuilder to return some JSON as response.

I have added JBuilder in my Gemfile.

# Gemfile
...
gem 'jbuilder', '~> 2.5'
...

# Gemfile.lock
...
jbuilder (2.8.0)
...

According to JBuilder documentation:

You can also extract attributes from array directly.

@people = People.all

json.array! @people, :id, :name

=> [ { "id": 1, "name": "David" }, { "id": 2, "name": "Jamie" } ]

Now, in my controller, I have added the following:

def index
  respond_to do |format|
    format.json { render json.array! User.all, :email, :full_name }
  end
end

But I get

NameError - undefined local variable or method `json' for UsersController:0x00007fe2f966f150 16:55:40 rails.1
| => Did you mean? JSON:

Am I missing anything here?

Upvotes: 5

Views: 10757

Answers (2)

H. Almidan
H. Almidan

Reputation: 518

You can do:

def index
  Jbuilder.new do |json|
    json.array! User.all, :email, :full_name
  end.attributes!
end

(It worked for me)

Source


Side note

You might see people doing:

Jbuilder.encode do |json|
 # ...
end

But Jbuilder.encode actually returns a string, as specified by this comment in the source code

Upvotes: 2

Vincent Rolea
Vincent Rolea

Reputation: 1663

You typically use jbuilder in a view file with the extension .json.jbuilder

in your controller:

def index 
  @users = User.all
  respond_to do |format|
    format.json 
  end
end 

in your app/views/users/index.json.jbuilder

json.array! @users, :email, :full_name

EDIT: you can do it from the controller like that as well:

format.json { render json: Jbuilder.new { |json| json.array! User.all, :email, :full_name  }.target! }

Upvotes: 13

Related Questions