Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, how to specify which fields to output in a controller's JSON response?

in my controller I currently have:

invite = Invite.find_by_token(params[:id])
user = invite.user

json_response({
  user: user
})

def json_response(object, status = :ok)
  render json: object, status: status
end

Right now, user is returning all user fields. I want to return just (id, email)... I've tried:

user = invite.user.select(:id, :email)
user = invite.user.pluck(:id, :email)

neither works. Ideas?

like image 467
AnApprentice Avatar asked Oct 26 '25 16:10

AnApprentice


1 Answers

You can use the method as_json passing attributes you want in the response, like:

user.as_json(only: [:id, :email])

like image 199
thaleshcv Avatar answered Oct 29 '25 07:10

thaleshcv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!