grape-entity icon indicating copy to clipboard operation
grape-entity copied to clipboard

how to call includes method before expose

Open lazybios opened this issue 8 years ago • 3 comments

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 avatar Apr 13 '17 11:04 lazybios

@lazybios did you find how to avoid n+1 queries ?

jonathanpa avatar Oct 03 '17 15:10 jonathanpa

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.

c0ze avatar Oct 04 '17 04:10 c0ze

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

Jayzen avatar Apr 03 '19 07:04 Jayzen