Ruby on rails 在Rocket Pants收集响应中引用方法(带参数)?
使用Rocket Pants gem作为API,我希望能够在Ruby on rails 在Rocket Pants收集响应中引用方法(带参数)?,ruby-on-rails,json,api,ruby-on-rails-4,rocketpants,Ruby On Rails,Json,Api,Ruby On Rails 4,Rocketpants,使用Rocket Pants gem作为API,我希望能够在集合json中返回一个自定义值。例如,我目前正在这样做: collection( current_user.prizes, include: { location: { only: [:title] } }, only: [:last_prize_at] ) 这将返回一个JSON响应,如下所示: { "response": [ { "location": { "title": "My
集合
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
)
#当前#u用户有一个名为“奖品#u from(location#u id)”的方法
收藏(
当前_用户奖,
包括:{location:{only:[:title]}},
仅限:[:最后一次获奖时间],
奖品列表:当前用户。奖品来自(:location\u id)#<此行无效
)
上面的代码显然不起作用,但是,它显示了我正在尝试做的事情。下面是一个示例响应,它应该是什么样子的:
{
"response": [
{
"location": {
"title": "My name"
},
"last_prize_at": "10-10-15",
"prize_list": [ # < here
{ .... }
]
}
],
"count": 1
}
{
“答复”:[
{
“地点”:{
“头衔”:“我的名字”
},
“最后一次获奖地点”:“10-10-15”,
“奖品清单”:[#
我如何才能做到这一点?我一直在寻找
方法
选项:
collection(
current_user.prizes,
include: { location: { only: [:title] } },
only: [:last_prize_at],
methods: [:user_prize_list] # Added line here
)
不幸的是,我还没有找到直接访问子方法的方法,也没有找到如何使用参数的方法。因此,为了使上述代码能够正常工作,我必须将其添加到我的位置
模型中:
def user_prize_list(location=nil, user=nil)
location ||= self
user ||= location.user
user.prizes_from(location.id)
end
不过它还是管用的