与所有子对象一起发送外键对象

时间:2019-04-15 07:59:59

标签: ruby-on-rails

有什么方法可以始终仅使用Rails API的应用程序与子对象或子对象一起检索父对象?

例如我有一个@students数组。 @students数组中的每个学生对象都有两个外键,分别是standard_id和school_id。现在,所有对象默认都具有standard_id和school_id。相反,我希望在@students数组中的每个学生对象中使用标准对象和学校对象。

我得到的回应

[
  {
    "id": 1,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:36:03.000Z",
    "updated_at": "2019-04-14T11:36:03.000Z"
  },
  {
    "id": 2,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:41:38.000Z",
    "updated_at": "2019-04-14T11:41:45.000Z"
  }
]

我想要的答复

[
  {
    "id": 1,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:36:03.000Z",
    "updated_at": "2019-04-14T11:36:03.000Z",
    "standard": {
      "id": 1,
      "name": "1",
      "created_at": "2019-04-14T11:32:15.000Z",
      "updated_at": "2019-04-14T11:32:15.000Z"
    },
    "school": {
      "id": 1,
      "name": "SACS",
      "created_at": "2019-04-14T11:35:24.000Z",
      "updated_at": "2019-04-14T11:35:24.000Z"
    }
  },
  {
    "id": 2,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:41:38.000Z",
    "updated_at": "2019-04-14T11:41:45.000Z",
    "standard": {
      "id": 1,
      "name": "1",
      "created_at": "2019-04-14T11:32:15.000Z",
      "updated_at": "2019-04-14T11:32:15.000Z"
    },
    "school": {
      "id": 1,
      "name": "SACS",
      "created_at": "2019-04-14T11:35:24.000Z",
      "updated_at": "2019-04-14T11:35:24.000Z"
    }
  }
]

所有控制器都有共同的解决方案吗?因为该应用程序已经构建。现在非常忙于在每个控制器中手动格式化数据。预先感谢。

1 个答案:

答案 0 :(得分:2)

如果您在控制器中使用Rails默认的as_json序列化程序,即参见下文:

render json: @students
# ^ above will default call `.to_json` to `@students`, which will also call `.as_json`
# thereby, equivalently calling:
# render json: @students.as_json

...然后,您可以稍微修改as_jsonsee docs),以便JSON将包含第一级嵌套关联;见下文

解决方案

app / models / student.rb

class Student < ApplicationRecord
  belongs_to :standard
  belongs_to :school

  def as_json(**options)
    unless options.has_key? :include
      options.merge!(include: [:standard, :school])
    end
    super(options)
  end

  # or if you don't want to manually include "each" association, and just dynamically include per association
  # def as_json(**options)
  #   unless options.has_key? :include
  #     options.merge!(
  #       include: self.class.reflect_on_all_associations.map(&:name)
  #     )
  #   end
  #   super(options)
  # end
end

全局解决方案(路径> = 5)

与上述解决方案相同,但如果您希望此方法适用于 ALL 模型,而不仅适用于Student模型,请执行以下操作:

app / models / application_record.rb

class ApplicationRecord < ActiveRecord::Base
  def as_json(**options)
    unless options.has_key? :include
      options.merge!(
        include: self.class.reflect_on_all_associations.map(&:name)
      )
    end
    super(options)
  end
end

用法示例

# rails console
students = Student.all
puts students.as_json
# => [{"id"=>1, "standard_id"=>1, "school_id"=>1, "created_at"=>"2019-04-14T11:36:03.000Z", "updated_at"=>"2019-04-14T11:36:03.000Z", "standard"=>{"id"=>1, "name"=>"1", "created_at"=>"2019-04-14T11:32:15.000Z", "updated_at"=>"2019-04-14T11:32:15.000Z"}, "school"=>{"id"=>1, "name"=>"SACS", "created_at"=>"2019-04-14T11:35:24.000Z", "updated_at"=>"2019-04-14T11:35:24.000Z"}}, {"id"=>2, "standard_id"=>1, "school_id"=>1, "created_at"=>"2019-04-14T11:41:38.000Z", "updated_at"=>"2019-04-14T11:41:45.000Z", "standard"=>{"id"=>1, "name"=>"1", "created_at"=>"2019-04-14T11:32:15.000Z", "updated_at"=>"2019-04-14T11:32:15.000Z"}, "school"=>{"id"=>1, "name"=>"SACS", "created_at"=>"2019-04-14T11:35:24.000Z", "updated_at"=>"2019-04-14T11:35:24.000Z"}}]

以上解决方案仅将第一级关联呈现为JSON响应的一部分,而不会“深度”呈现第二级或第三级等关联。

已更新(带有分页):

我很好奇您提出的整合分页的请求;因此,下面是我可能的解决方案(经过测试,尽管尚不确定是否有副作用):

您将需要一个“分页”宝石,即在下面的示例中,我正在使用kaminari

app / models / application_record.rb

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def as_json(**options)
    unless options.has_key? :include
      options.merge!(
        include: self.class.reflect_on_all_associations.map(&:name).inject({}) do |hash, name|
          paginate = options.dig(:association_paginations, name.to_sym, :paginate)
          paginate = true if paginate.nil?
          page = options.dig(:association_paginations, name.to_sym, :page) || 1
          per = options.dig(:association_paginations, name.to_sym, :per) || Kaminari.config.default_per_page

          hash[name.to_sym] = {
            paginate: paginate,
            page: page,
            per: per
          }
          hash
        end
      )
    end
    super(options)
  end
end

app / config / initializers / active_model_serialization_patch.rb

module ActiveModel::Serialization
  private def serializable_add_includes(options = {})
    if Gem.loaded_specs['activemodel'].version.to_s != '6.0.0.beta3' # '5.2.3'
      raise "Version mismatch! \
        Not guaranteed to work properly without side effects! \
        You'll have to copy and paste (and modify) to below correct code (and Gem version!) from \
        https://github.com/rails/rails/blob/5-2-stable/activemodel/lib/active_model/serialization.rb#L178"
    else
      # copied code: start
      return unless includes = options[:include]

      unless includes.is_a?(Hash)
        includes = Hash[Array(includes).flat_map { |n| n.is_a?(Hash) ? n.to_a : [[n, {}]] }]
      end

      includes.each do |association, opts|
        if opts[:paginate]
          opts[:page] ||= 1
          opts[:per] ||= Kaminari.config.default_per_page
          records = send(association).page(opts[:page]).per(opts[:per])
        else
          records = send(association)
        end

        if records
          yield association, records, opts
        end
      end
      # copied code: end
    end
  end
end

app / config / initializers / active_record_relation_patch.rb

class ActiveRecord::Relation
  def as_json(**options)
    if options[:paginate]
      options[:page] ||= 1
      options[:per] ||= Kaminari.config.default_per_page
      options[:paginate] = false
      page(options[:page]).per(options[:per]).as_json(options)
    else
      super(options)
    end
  end
end

your_controller.rb

def some_action
  @students = Student.all

  render json: @students.as_json(
    paginate: true,
    page: params[:page],
    per: params[:per],
    association_paginations: params[:association_paginations]
  )
end

示例请求1

http://localhost:3000/your_controller/some_action?per=2&page=1

示例响应1

因为per = 2

,只有两名学生返回
[
  {
    id: 1,
    school_id: 101,
    school: { id: 101, ... },
    standard_id: 201,
    standard: { id: 201, ... },
    subjects: [
      { id: 301, ... },
      { id: 302, ... },
      { id: 303, ... },
      { id: 304, ... },
      { id: 305, ... },
      ...
    ],
    attendances: [
      { id: 123, ... },
      { id: 124, ... },
      { id: 125, ... },
      { id: 126, ... },
      { id: 127, ... },
      { id: 128, ... },
      ...
    ]
  },
  {
    id: 2,
    ...
  }
]

示例请求2

http://localhost:3000/your_controller/some_action?per=2&page=1&association_paginations[subjects][per]=2

示例响应2

因为per = 2

,只有两名学生返回

由于association_paginations[subjects][per] = 2

,仅返回了两个主题
[
  {
    id: 1,
    school_id: 101,
    school: { id: 101, ... },
    standard_id: 201,
    standard: { id: 201, ... },
    subjects: [
      { id: 301, ... },
      { id: 302, ... },
    ],
    attendances: [
      { id: 123, ... },
      { id: 124, ... },
      { id: 125, ... },
      { id: 126, ... },
      { id: 127, ... },
      { id: 128, ... },
      ...
    ]
  },
  {
    id: 2,
    ...
  }
]

P.S。由于上述解决方案涉及猴子补丁,因此我建议您改用ActiveModelSerializers::Model,因为您请求的功能现在变得越来越复杂。