使用所有子对象或子对象发送外键对象

问题描述 投票:0回答:1

有没有办法总是使用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"
    }
  }
]

所有控制器都有通用解决方案吗?因为应用程序已经构建。现在非常忙于在每个控制器中手动格式化数据。提前致谢。

ruby-on-rails
1个回答
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将包含第一级嵌套关联;见下文

应用程序/模型/ 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

全局解决方案(Rails> = 5)

与上面的解决方案相同,但是如果您希望这适用于所有模型而不仅仅适用于Student模型,那么以下内容:

应用程序/模型/ 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

Usage Example

# 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

应用程序/模型/ 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

应用程序/配置/初始化/ 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

应用程序/配置/初始化/ 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

Example Request 1

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

Example Response 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,
    ...
  }
]

Example Request 2

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

Example Response 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,
    ...
  }
]

附:因为上面的解决方案涉及猴子修补,我建议使用ActiveModelSerializers::Model,因为您要求的功能现在变得复杂。

© www.soinside.com 2019 - 2024. All rights reserved.