ruby-on-rails (Ruby on Rails active_model_serializers)如何在与ActiveModel::Serializer的2级深度关联中将嵌套哈希向上移动一级?

qyzbxkaa  于 2023-05-30  发布在  Ruby
关注(0)|答案(1)|浏览(103)

我在Ruby on Rails中有以下ActiveRecord关联:

class Driver
  has_one :car
  delegate :tires, to: :car
end
class Car
  belongs_to :driver
  has_many   :tires
end
class Tire
  belongs_to :car
end

我有以下序列化器:

class DriverSerializer < ActiveModel::Serializer
  attributes :id, :name

  has_one :car

  class CarSerializer < ActiveModel::Serializer
    attributes :id

    has_many :tires

    class TireSerializer < ActiveModel::Serializer
      attributes :id
    end
  end

end

生成的JSON看起来像这样:

{
  "id": 1,
  "name": "Bob",
  "car": {
    "id": 1,
    "tires": [
      {
        "id": 1
      },
      {
        "id": 2
      }
      ...
    ]
  }
}

但是我希望tires向上移动一级,以便直接嵌套在driver下面。我想按原样利用序列化器,而不使用Ruby的map方法。我知道我能做到:

class DriverSerializer < ActiveModel::Serializer
  attribute :tires

  def tires
    object.tires.map{|t| TireSerializer.new(t)}
  end
end

但是,有没有更简单的方法来将哈希值向上移动一级?

2sbarzqh

2sbarzqh1#

我认为最好在Driver模型中为tires属性使用has_one :tires, through: :car关联,而不是将其委托给:car。然后,可以将DriverSerializer中的has_many选项用于此属性,并将TireSerializer用于其序列化器。

class Driver
  has_one :car
  has_many :tires, through: :car
end

在Driver serializer中

class DriverSerializer < ActiveModel::Serializer
  has_many :tires, serializer: TireSerializer
end

相关问题