【问题标题】:Reference a method (with argument) in the Rocket Pants collection response?在 Rocket Pants 集合响应中引用方法(带参数)?
【发布时间】: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


    【解决方案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
    

    虽然有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2013-05-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多