【问题标题】:How to configure the JSON response when using rocket pants?使用火箭裤时如何配置 JSON 响应?
【发布时间】:2012-07-15 16:02:29
【问题描述】:

我正在使用火箭裤来呈现我的 JSON API。

我试图通过在我的模型中覆盖 as_json 来改变它呈现 JSON 的方式,但不知何故,它似​​乎没有改变火箭裤响应中的任何内容。

在我的控制器中:

class Api::V1::ProjectsController < RocketPants::Base
  ...
  def show
    expose Project.find(params[:id])
  end
  ...
end

在我的模型中:

class Project < ActiveRecord::Base
  ...
  def as_json(options = {})
    {"this" => "is not working!"}
  end
  ...
end

我错过了什么?

【问题讨论】:

  • 我从没听说过火箭裤,但不是to_json 吗?

标签: ruby-on-rails ruby-on-rails-3 json api rest


【解决方案1】:

此外,还有第一组可以发送到暴露块的选项。根据来源,您可以将选项传递给 serializable_hash 方法。例如:

expose user, only: [:name, :email]

这将在具有名称和电子邮件的对象上调用 serializable_hash。

您还可以在这组选项中指定预加载。例如:

expose uploads, :include =&gt; { :user =&gt; { :only =&gt; :username } }。

这将公开您的上传并急切加载与用户的 belongs_to 关联。

来源:https://github.com/filtersquad/rocket_pants/issues/20#issuecomment-6347550

【讨论】:

    【解决方案2】:

    我已经想出了如何做到这一点。火箭裤的工作方式是查看serializable_hash 方法。覆盖它会导致响应发生变化。

    编辑:

    我得到的解决方案:

    在我需要添加一些属性的模型中:只需覆盖属性方法:

     # Overriding this method is required for the attribute to appear in the API
      def attributes
        info = {} # add any logic that fits you
    
        super.merge info
      end
    

    在需要公开 API 的控制器中,我创建了一个新的 Model 类(这只是为了保持不同的 API 版本需要),并重写了 serializable_hash 方法:

      class Location < ::Location 
        def serializable_hash(options = {})
          super only: [:id, :lat, :long],
                include: [user: {only: ...your attributes here...}]
        end
      end
    

    【讨论】:

    • 任何机会你都可以提供一些例子,因为火箭裤的文档在这方面有点缺乏。
    • 我已在答案中添加了详细信息。
    【解决方案3】:

    对于嵌套的东西:

    paginated @matches, include: { listing: { include: { company: { only: [:name, :email] } } } }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      相关资源
      最近更新 更多