0

我正在添加带有葡萄宝石的 REST api。我还添加了葡萄实体宝石。我需要的是来自这三个模型的数据:Product、Company 和 ManufactureCompany 在一个 json 文件中。

中的关系product.rb

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

products.rb文件:

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

并且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

实体可能是错误的。我看到有一个 has_many 关系你可以说expose :something, using: Entities::RelatedModel,但在这种情况下,相关模型只有 product_id 和 company_id (和自己的 id)。在网上找不到任何例子。

4

1 回答 1

0

我找不到我想要的东西,但我找到了另一种选择。我不得不放弃实体。我这样定义 Products 类:

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
于 2014-08-06T09:32:59.587 回答