【发布时间】:2015-10-27 03:06:38
【问题描述】:
将 Rocket Pants gem 用于 API,我希望能够在 collection json 中返回自定义值。例如,我目前正在这样做:
collection(
current_user.prizes,
include: { location: { only: [:title] } },
only: [:last_prize_at]
)
这会返回如下 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
}
我怎样才能做到这一点?
【问题讨论】:
标签: ruby-on-rails json api ruby-on-rails-4 rocketpants