【发布时间】:2014-12-02 01:59:15
【问题描述】:
我已经将 AMS (0.8) 与 Rails 3.2.19 一起使用,但我真正遇到的一个问题是如何控制序列化程序是否包含它们的关联。我显然使用 AMS 来构建 JSON 蜜蜂。有时,序列化程序是叶元素或最远的元素,有时它是顶级元素,需要包含关联。我的问题是最好的方法是什么,或者我在工作下面做的解决方案是什么(或者是最好的解决方案)。
我看到了一些讨论,但我发现它们非常令人困惑(并且基于版本)。很明显,对于 Serializer 属性或关联,有一个 include_XXX?方法,你可以在这里返回一个真实或虚假的陈述。
这是我提出的代码 - 这是一个拥有许多 wine_items 的酿酒师。你会这样做吗?
模型类:
class WineItem < ActiveRecord::Base
attr_accessible :name, :winemaker_id
belongs_to :winemaker
end
class Winemaker < ActiveRecord::Base
attr_accessible :name
has_many :wine_items
attr_accessor :show_items
end
序列化器:
class WinemakerSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :wine_items
def include_wine_items?
object.show_items
end
end
class WineItemSerializer < ActiveModel::Serializer
attributes :id, :name
end
在我的控制器中:
class ApiWinemakersController < ApplicationController
def index
@winemakers=Winemaker.all
@winemakers.each { |wm| wm.show_items=true }
render json: @winemakers, each_serializer: WinemakerSerializer, root: "data"
end
end
【问题讨论】:
-
AMS 0.10.2:它不起作用。
def include_wine_items?无效 - 无论返回 true 还是 false 都包含关联。
标签: ruby-on-rails active-model-serializers