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.
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: