Grape entities with has_many through relationships

1.6k Views Asked by At

I'm adding REST api with the grape gem. I also added the grape-entities gem. What I need is that data from these three models: Product, Company and ManufactureCompany in one json file.

The relationships in product.rb:

has_many :manufacture_companies
has_many :manufacturers, :through => :manufacture_companies, :source => :company

The products.rb file:

class Products < Grape::API
  resource :products do
    get do
        @products = Product.all
        present @products, with: Entities::Product
    end
  end
end

And entities.rb:

class Product < Grape::Entity
  expose :id, :name,:description, :barcode
  expose :net_weight, :reference_unit
  expose :prepare_instructions, :storage_instructions, :origin
  expose :manufacturers, using: Entities::Company
end

class Company < Grape::Entity
  expose :id
  expose :name
end

The entities are probably wrong. I saw that with a has_many relationship you can just say expose :something, using: Entities::RelatedModel but in this case, the related model has only product_id and company_id (and own id). Couldn't find any example on the net.

1

There are 1 best solutions below

0
On

I couldn't find exaclty what I want, but I found an alternative. I had to give up from Entities. I defined the Products class like this:

module API
# Projects API
  class Products < Grape::API
    resource :products do
      get do
        @products = Product.all.as_json(include: 
          [{distributors: {only: [:id, :name, :address, :phone, :fax, :email, :website, :pib]}}, 
          {manufacturers: {only: [:id, :name, :address, :phone, :fax, :email, :website, :pib]}},
       :photos,
          {ingredients: {only: [:name, :alternative_name, :description]}},
          #...
       ], 
        only: [:id, :name, :barcode, :description, :prepare_instructions, :storage_instructions, :net_weight, :reference_unit, :origin]
        )
     end
    end
  end
end