ruby-on-railsmongodbruby-grapegrape-entity

How to use grape entity based on value of a field?


Anyone worked on Grape & Grape entity i have an issue. db: Mongoid I have two models 1. User 2. Answers

every user have package_type: 1 or 2 or 3 and every answer also have package type in array but of single value. LIKE [1] or [2] or [3].

I want to send those answer in response which have package_type == users.package_type.

user_entity:

expose :answers, as: :profile_info, using: API::V1::Entities::Answer 

answer_entity:

module API
    module V1
        module Entities
            class Answer < Grape::Entity
                expose :answer
                expose :question
                expose :package_type
            end
        end
    end
end

Solution

  • you can do that filtering from the relation

    class User
      has_many :answers, -> { where({answers: {package_type: self.package_type}}) }
    end
    

    or from the entity

    expose :profile_info do |user, _options| 
      API::V1::Entities::Answer.represent(user.answers.where({answers: {package_type: user.package_type}}))
    end