Rails 4如何合并2个数组

时间:2015-08-12 12:14:36

标签: ruby-on-rails

我有2个数组,里面填充了sql查询提供的信息。 我的第一个数组是Reviews数组将返回此JSON对象:

{
  "response": [
    {
      "score": 4,
      "comment": "Probably some comment",
      "first_name": "Doe",
      "id": 1
    }
 ]

}

第二个是Cleaners数组,必须返回这个json:

{
      "response": [
        {
          "id": 2,
          "authentication_id": 3,
          "first_name": "Consuela",
          "last_name": "Ernandez",
          "avg_rating": 3,
          "postcode": "AX13D2",
          "created_at": "2015-08-05T10:39:28.957Z",
          "updated_at": "2015-08-05T10:49:59.509Z",
          "phone_number": "Consueala's phone number",
          "status": "approved",
          "is_ok_with_pets": true
        }

到目前为止一直这么好,但我必须得到的最终结果是合并这两个数组并渲染结果并为每个清洁工添加平均评级:

    {
      "response": [
        {
          "id": 1,
          "authentication_id": 3,
          "first_name": "Consuela",
          "last_name": "Ernandez",
          "postcode": "AX13D2",
          "avg_rating": 3,
          "created_at": "2015-08-05T10:39:28.957Z",
          "updated_at": "2015-08-05T10:49:59.509Z",
          "phone_number": "Consueala's phone number",
          "status": "approved",
          "is_ok_with_pets": true
          "reviews": [
                {
              "score": 4,
              "comment": "Probably some comment",
              "first_name": "Doe",
              "id": 1
                  }
                ]
              }
           }

1 个答案:

答案 0 :(得分:1)

如果Cleaner has_many Review,则可以执行以下操作:

Cleaner.includes(:reviews).find(yourid).as_json(include: [:reviews])

哪个会提供你想要的json。您可以使用to_json使用相同的选项直接获取字符串。

如果你想为每个清洁工包括avg_rating,我建议采用以下方法:

class Cleaner < ActiveRecord::Base

  def avg_rating
    # yourlogic
  end

  def as_json(**options)
    super(options.merge(methods: [:avg_rating]))
  end

end

或者如果你只想为那个控制器做,你可以这样做:

Cleaner.includes(:reviews).find(yourid).as_json(include: [:reviews], methods: [:avg_rating])