ruby-grape / grape-active_model_serializers

User active_model_serializers with Grape
MIT License
140 stars 68 forks source link

not working on custom json response #46

Closed khacluan closed 8 years ago

khacluan commented 9 years ago

I tried to response user with serialize, but not success

class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :email
end

class Registrations < Grape::API
   resource :users do
      get "/" do
         {"message": "Hello", user: User.first}
      end
   end
end

I want result like that {message: "hello", user: {id: 1, first_name: "A", last_name: "B", email: "abc@gmail.com"}} but it response all attributes of User

dblock commented 9 years ago

Seems problematic, you should build a test case here for this to begin with.

drn commented 8 years ago

@khacluan this is many months late, but you can use ASM's meta functionality to achieve your use-case. Try this:

class Registrations < Grape::API
   resource :users do
      get "/", meta_key: message, meta: 'Hello' do
         user
      end
   end
end

something like this would also work if you need to programmatically define the message

class Registrations < Grape::API
   resource :users do
      get "/" do
         render user, meta_key: message, meta: 'Hello'
      end
   end
end

I'm going to close this issue, as it is almost a year old. If the above doesn't work, please open a new issue.