使用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
}
我怎样才能做到这一点?
答案 0 :(得分:0)
我正在寻找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
虽然有效!