0

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.

DR_
  • 174
  • 1
  • 2
  • 14
  • So what happens when you try the code you've got? –  Aug 05 '14 at 12:39
  • @SimonSouth 500 Internal Server Error – DR_ Aug 05 '14 at 12:46
  • Do you have a stack trace, or some other indication of which line of code is causing the error? –  Aug 05 '14 at 13:00
  • The problem is that the manufacturers have two foreign keys. It needs to know the proudct_id and company_id. So even if I said :manufacturers (this can be any name (not even the attrib in the model)) there's no connection to the middle table. No idea how to write it. I tried every combination. (using: Entities::ManufactureCompany ... ) – DR_ Aug 05 '14 at 13:05
  • What is the error message you're seeing? Your code not only looks correct to me but so far (from the Rails console) is working correctly for me as well. –  Aug 05 '14 at 15:26
  • The error message in the one from the first answer (Internal Server Error). Hm, interesting. Doesn't work for me. BTW, you need to access the json data with `localhost:3000/api/v1/products.json` – DR_ Aug 06 '14 at 06:52

1 Answers1

0

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
DR_
  • 174
  • 1
  • 2
  • 14