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

但我不知道如何将 current_user 发送到葡萄实体模型:

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 回答
0

另一种方法是通过定义属性访问器将当前用户临时存储在项目中:

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

  def user_likes
    likers.include?(current_user)
  end
end

并在葡萄 api 中设置当前用户:

get :id do
  item = Item.find(.....)
  item.current_user = current_user
  present item, with: FancyApp::Entities::Item
end

不需要对葡萄实体模型进行任何更改。
没有数据库字段current_user_id左右。没有写入数据库。

于 2020-10-07T09:23:04.063 回答