知道如何通过关联在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'
答案 0 :(得分:-1)
Edit: the answer below is relevant to AMS 0.8. There are better ways to do this in more recent versions.
You can't have two serializers that has_many
/ has_one
each other. The fix is to create a "short" serializer for each model to be used inside of a related serializer.
For example,
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