I want to show only the emails of my users, this is my controller
def all
Jbuilder.new do |json|
json.array! User.all, :email
end
I am trying to do that using jbuilder, but when I do the request, it does not give nothing
It say:
No template found for Api::V1::UserController#all, rendering head :no_content
this is my route:
Rails.application.routes.draw do
mount Sidekiq::Web => '/internal/sidekiq'
mount Flipper::UI.app(Flipper,
{ rack_protection:
{ except: %i[authenticity_token form_token json_csrf remote_token http_origin
session_hijacking] } }), at: '/internal/flipper'
namespace :api do
namespace :v1, defaults: { format: :json} do
get '/all', to: 'users#all'
end
end
end
CodePudding user response:
Firstly you need to assign instance varible in the controller action to pass it to jbuider view
def all
@users = User.all
end
Than build JSON in app/views/api/v1/user/all.json.jbuilder
. BTW controller names are usually plural, users
is better than user
json.array! @users, :email, :name
It will generate JSON like this
[{ "email": "email1", "name": "Name1" }, { "email": "email2", "name": "Name2" }]
CodePudding user response:
The code you are showing looks like its missing an end
for your do
block - thats not the error though.
Without further digging I think you might not have a corresponding view file, something like views/users/index.json.jbuilder. inside there you might want to stick your jbuilder stuff (going with the rails convention):
# users_controller.rb
def index
@users = User.all
end
# views/users/index.json.jbuilder
json.array! @users do |user|
json.extract! user, :email, :name
end
you are using an all
action in your controller however and if your route for that is fine you can swap index for all
# users_controller.rb
def all
@users = User.all
end
# views/users/all.json.jbuilder
json.array! @users do |user|
json.extract! user, :email, :name
end
its always good to take a look at the docs when you bump up against this kinda stuff: jbuilder gem