3

グレープエンティティを使用してモデルメソッドに引数を渡すにはどうすればよいですか?

アイテムを提示するときに current_user がアイテムを気に入るかどうかを確認したいので、モデルuser_likes?メソッドを作成しました。

class Item
  include Mongoid::Document
  #some attributes here...
  has_and_belongs_to_many :likers

  def user_likes?(user)
    likers.include?(user)
  end
end

しかし、現在のユーザーをグレープエンティティモデルに送信する方法がわかりません:

module FancyApp
  module Entities
    class Item < Grape::Entity
      expose :name #easy
      expose :user_likes # <= How can I send an argument to this guy ?
    end 
  end
end

ブドウのAPIで:

get :id do
  item = Item.find(.....)
  present item, with: FancyApp::Entities::Item # I should probably send current_user here, but how ?
end

current_user はおそらくこの最後のコードから送信されるべきだと思いますが、その方法がわかりません:(

何かご意見は ?ありがとう !

4

3 に答える 3

7

currentさて、パラメーターとして渡して、ブロックで使用できることがわかりました。そう :

present item, with: FancyApp::Entities::Item, :current_user => current_user 

およびエンティティ定義では:

expose :user_likes do |item,options|
  item.user_likes?(options[:current_user])
end
于 2014-04-19T18:12:53.700 に答える
0

@aherve、何らかの理由で、私の場合は構文が機能しません。Grape Entity ドキュメントの構文は少し異なります

あなたの例では、構文は次のようになります。

expose(:user_likes) { |item, options| item.user_likes?(options[:current_user]) }
于 2017-08-29T18:19:08.973 に答える