【问题标题】:Putting instance method results (with arguments) into active_model_serializers将实例方法结果(带参数)放入 active_model_serializers
【发布时间】:2016-05-18 09:49:44
【问题描述】:

我正在制作 JSON API 并希望从我的数据库中序列化 recipe 记录。在 JSON 响应中,我想包含 @recipe.is_favorited_by?(current_user) 的输出以及 recipe 的一些属性。

我从the docs 看到我可以调用:render json: @recipe, methods: :is_favorited_by? - 但我不确定如何将 current_user 作为参数传递。

我需要打什么电话才能在响应中包含@recipe.is_favorited_by?(current_user) 的结果?

【问题讨论】:

    标签: ruby ruby-on-rails-4 active-model-serializers


    【解决方案1】:

    您可以将current_user 属性添加到您的模型并在您的json 执行之前设置它。

    查看stackoverflow问题链接Ruby to_json :methods arguments

    【讨论】:

    • 感谢您的帮助,但我想知道是否有更可扩展的方式来执行此操作。如果有其他方法需要其他参数,如果我使用这种方法,我将不得不为每个方法都这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多