ruby-on-railsruby-grapegrape-apigrape-entity

grape-entity and has_many requires explicit entity


I'm using grape and grape-entity in a Rails 4.2.1 project, and I'm running into a weird error with presenting using the right model.

According to the documentation, organizing my entities within each model results in this:

Grape will automatically detect the Entity class and use it to present your models.

In addition, the documentation also says:

By default every object of a collection is wrapped into an instance of your Entity class.

Here's the code I have now.

class User < ActiveRecord::Base
  class Entity < Grape::Entity
    expose :id, :name
    expose :addresses
  end
end

class Address < ActiveRecord::Base
  class Entity < Grape::Entity
    expose :id, :street1
  end
end

If I don't do expose :addresses, with: Address:Entity, it doesn't work, and still exposes all the fields of the address. Any reason it's not automatically detecting the correct entity?


Solution

  • Turns out this is expected behavior. Grape only detects the entity class that's nested within the model, so it doesn't know to use the entity class of any associated records.

    There's a feature request filed here (which is also where I got this from):