2

我正在使用火箭裤来呈现我的 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

我错过了什么?

4

3 回答 3

8

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

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

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

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

expose uploads, :include => { :user => { :only => :username } }.

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

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

于 2013-05-23T15:18:23.160 回答
5

我已经想出了如何做到这一点。火箭裤的工作方式是看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
于 2012-07-30T16:06:18.037 回答
0

对于嵌套的东西:

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

于 2014-04-04T15:26:33.207 回答