【问题标题】:SystemStackError (stack level too deep) using Active model SerializerSystemStackError (stack level too deep) 使用 Active model Serializer
【发布时间】:2015-09-11 16:49:40
【问题描述】:

知道如何通过关联在 has_many 中实现 active_mode_serializer。

我有三个模型:

class Menu < ActiveRecord::Base
    has_many :menu_details, inverse_of: :menu, dependent: :destroy
    has_many :foods, through: :menu_details
end

class Food < ActiveRecord::Base
    has_many :menu_details
    has_many :menu, through: :menu_details
ends

class MenuDetail < ActiveRecord::Base
    belongs_to :menu
    belongs_to :food
end

活动模型序列化器

class MenuSerializer < ActiveModel::Serializer
  attributes :id, :name, :price
  has_many :menu_details
  has_many :foods
end

class MenuDetailSerializer < ActiveModel::Serializer
  attributes :id

  has_one :menu
  has_one :food
end

class FoodSerializer < ActiveModel::Serializer
  attributes :id

  has_many :menu_details
  has_many :menu

end

我总是收到此错误:

Completed 500 Internal Server Error in 24ms

SystemStackError (stack level too deep):
 app/controllers/menus_controller.rb:7:in `all'

【问题讨论】:

  • 我的序列化器结构是否正确?这就是为什么我得到那个错误。我不知道如何在has_many through 中使用它。

标签: ruby-on-rails ruby activerecord serialization


【解决方案1】:

编辑:下面的答案与 AMS 0.8 相关。在较新的版本中有更好的方法来做到这一点。

您不能有两个has_many / has_one 彼此的序列化程序。解决方法是为每个模型创建一个“短”序列化器,以便在相关序列化器内部使用。

例如,

class MenuSerializer < ActiveModel::Serializer
  attributes :id, :name, :price
  has_many :menu_details, serializer: MenuDetailShortSerializer
  has_many :foods, serializer: FoodShortSerializer
end

class MenuDetailShortSerializer < ActiveModel::Serializer
  attributes :id
end

class FoodShortSerializer < ActiveModel::Serializer
  attributes :id
end

【讨论】:

  • v9 中的“更好的方法”是什么?
猜你喜欢
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2015-07-03
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多