在 Rocket Pants 集合响应中引用方法(带参数)?

Reference a method (with argument) in the Rocket Pants collection response?

将火箭裤 gem 用于 API,我希望能够 return collection json 中的自定义值.例如,我目前正在这样做:

collection(
  current_user.prizes,
  include: { location: { only: [:title] } },
  only: [:last_prize_at]
)

此 return 是一个 JSON 响应,如下所示:

{
  "response": [
    {
      "location": {
        "title": "My name"
      },
      "last_prize_at": "10-10-15"
    }
  ],
  "count": 1
}

这非常简单,并且可以正常工作。

我想要做的是在响应中引用一个带有参数的方法,例如:

# current_user has a method called "prizes_from(location_id)"
collection(
  current_user.prizes,
  include: { location: { only: [:title] } },
  only: [:last_prize_at],
  prize_list: current_user.prizes_from(:location_id)   # < this line doesn't work
)

上面的代码显然不起作用,但是,它显示了我正在尝试做的事情。这是它应该是什么样子的示例响应:

{
  "response": [
    {
      "location": {
        "title": "My name"
      },
      "last_prize_at": "10-10-15",
      "prize_list": [                # < here
        { .... }
      ]           
    }
  ],
  "count": 1
}

我怎样才能做到这一点?

methods 选项正是我要找的:

collection(
  current_user.prizes,
  include: { location: { only: [:title] } },
  only: [:last_prize_at],
  methods: [:user_prize_list]        # Added line here
)

不幸的是,我还没有找到能够直接访问子方法或如何使用参数的方法。因此,为了使上面的代码起作用,我必须将其添加到我的 Location 模型中:

def user_prize_list(location=nil, user=nil)
  location ||= self
  user ||= location.user
  user.prizes_from(location.id)
end

虽然有效!