【问题标题】:passing argument to model method with grape-entity将参数传递给具有葡萄实体的模型方法
【发布时间】:2014-04-19 17:49:35
【问题描述】:

如何使用葡萄实体将参数传递给模型方法?

我想在展示物品的时候检查一下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,但我不知道该怎么做:(

有什么想法吗? 谢谢!

【问题讨论】:

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


    【解决方案1】:

    好吧,我发现我可以将current 作为参数传递,并在一个块中使用它。所以:

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

    在实体定义中:

    expose :user_likes do |item,options|
      item.user_likes?(options[:current_user])
    end
    

    【讨论】:

    • 它可能会让你这样做,但这并不意味着它是最好的方法。按照我建议的方式清洁。
    • @Oliver Barnes 我是 Grape 实体的新手,您能否详细说明您的建议如何更简洁?在我看来,在您的建议中,您正在更改数据库中的实际记录只是为了将其传递给实体,这对我来说似乎并不干净。
    • 我实际上建议不要在任何情况下使用update_attributes。它确实执行了数据库更改,您绝对不希望这样做。如果两个用户同时请求您的路线,那么您很有可能会为至少一个用户混合 current_user 值。
    • 没错,不知道我在想什么。可能匆忙回答 - 已删除
    【解决方案2】:

    @aherve,由于某种原因,您的语法在我的情况下不起作用。 Grape Entity docs 中的语法有点不同

    你的例子,语法应该是:

    expose(:user_likes) { |item, options| item.user_likes?(options[:current_user]) }
    

    【讨论】:

      【解决方案3】:

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

      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左右。没有写入数据库。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-13
        • 1970-01-01
        • 2014-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-22
        相关资源
        最近更新 更多