ruby-on-railsjbuilder

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?


Solution

  • 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! }