具有has_many关系的葡萄实体

时间:2014-08-05 09:35:59

标签: ruby-on-rails grape grape-api grape-entity

我添加了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)。无法在网上找到任何例子。

1 个答案:

答案 0 :(得分: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