Gem grape 如何编写有多态关联的 api?

stephen · 2013年11月02日 · 最后由 victorialice 回复于 2016年11月18日 · 3334 次阅读

grape 如何编写有多态关联的 api? 好似直接 expose 是不行的! picture.rb

class Picture
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::BaseModel

  mount_uploader :image, ImageUploader

  attr_accessor :uploader_secure_token
  attr_accessible :image

  belongs_to :imageable, :polymorphic => true
end

product.rb

class Product
  has_many :pictures, :as => :imageable, :dependent => :destroy
end

entity.rb

class Product < Grape::Entity
   expose :id, :name, :cover
end

class DetailProduct < Grape::Entity
   expose :id, :name, :howmany, :price, :exprice, :dprice, :mprice, :inprice, :size, :use, :feature, :inventory,
                    :sales, :cover, :selling, :barcode, :special_offer
   expose :pictures, :using => APIEntities::Picture
end

class Picture < Grape::Entity
  expose :image
end

api.rb

resource :products do
      get do
        @products = Product.limit(20)
        present @products, :with => APIEntities::DetailProduct
      end

      get ":id" do
        @product = Product.includes(:pictures).find(params[:id])
        present @product, :with => APIEntities::DetailProduct
      end
end

如果你的 Grape 不是跟 Rails 一起用的话,请问你的 mount_uploader 能用么?

@Victor 那直接提取保存在数据库的 url 吗?还是有其他解决办法?

#2 楼 @stephen 我们第一版本 api 是用 rails 的 controller 和 model 凑合写。第 2 版重构的时候据说 grape 很牛。用 rails 很慢。所以就直接用 grape 写了。返回图片这部分我搞了很久也不行。没办法就自己写了点代码。返回不同版本的数据库的 url。

楼主 怎么 expose image 的 url 啊 求解答 class Picture < Grape::Entity expose :image end

需要 登录 后方可回复, 如果你还没有账号请 注册新账号