grape-entity
grape-entity copied to clipboard
how to call includes method before expose
I use grape entity in below way. And got a n+1 warning in expose :roles methods. I need know how can I call includes(:roles) methods before exposed. Thks!
Model
class User
has_many :roles
end
class Role
belongs_to :user
end
Entity
class User < Grape::Entity
expose :roles do |obj, _opts|
obj.roles.map(&:name)
end
end
@lazybios did you find how to avoid n+1 queries ?
I think you need to call includes in the controller, when fetching the objects from db.
something like
respond_with User.where(your_params).includes(:roles), with: UserEntity
not sure this can be done at the entity layer.
call includes in the model will solve the N+1 warning
class User
has_many :roles
def roles
self.where(your_params).includes(:roles)
end
end