ruby-grape / grape-active_model_serializers

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

:serializer option not working on collection as a result requests #23

Closed masciugo closed 10 years ago

masciugo commented 10 years ago

Hi, I'm using grape-active_model_serializers-1.2.1 in a Rails 4.1.5 project. Specifying a different serializer works only for single instance

resources :items do
  desc "Return all items"
  get '', :serializer => WhiteItemSerializer do
    Item.all
  end

  desc "Return a item"
  params do
    requires :id, type: String, desc: "ID of the item"
  end
  get ":id", :serializer => WhiteItemSerializer  do
    Item.where(id: permitted_params[:id]).first!
  end

end

GET /api/v1/items/{id} works while GET /api/v1/items raises an exception:

NoMethodError at /api/v1/items
==============================

> undefined method `read_attribute_for_serialization' for #<Item::ActiveRecord_Relation:0x007f9065781cf0>

activerecord (4.1.5) lib/active_record/relation/delegation.rb, line 136
-----------------------------------------------------------------------

``` ruby
  131         elsif array_delegable?(method)
  132           to_a.public_send(method, *args, &block)
  133         elsif arel.respond_to?(method)
  134           arel.public_send(method, *args, &block)
  135         else
> 136           super
  137         end
  138       end
  139     end
  140   end

App backtrace

Full backtrace

jakecraige commented 10 years ago

You need to use each_serializer instead of serializer when it's an array of items

masciugo commented 10 years ago

ok! I should have seen it in the readme even if it's not so didascalic. Thank you!