【问题标题】:how to conditionally include associations in a Rails Active Model Serializer v0.8如何有条件地在 Rails Active Model Serializer v0.8 中包含关联
【发布时间】: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


【解决方案1】:

我自己遇到了这个问题,这是迄今为止最干净的解决方案(但我不喜欢它)。

此方法允许您执行以下操作:

/parents/1?include_children=true

或使用更简洁的语法,例如:

/parents/1?include=[children]等...

# app/controllers/application_controller.rb
class ApplicationController
  # Override scope for ActiveModel-Serializer (method defined below)
  # See: https://github.com/rails-api/active_model_serializers/tree/0-8-stable#customizing-scope
  serialization_scope(:serializer_scope)

  private

  # Whatever is in this method is accessible in the serializer classes.
  # Pass in params for conditional includes.
  def serializer_scope
    OpenStruct.new(params: params, current_user: current_user)
  end
end

# app/serializers/parent_serializer.rb
class ParentSerializer < ActiveModel::Serializer
  has_many :children

  def include_children?
    params[:include_children] == true
    # or if using other syntax:
    # params[:includes].include?("children")
  end
end

对我来说有点骇人听闻,但它确实有效。希望对您有用!

【讨论】:

  • AMS 0.10.2:它不起作用。 def include_children?没有效果 - 无论它返回 true 还是 false 都包含关联。
猜你喜欢
  • 1970-01-01
  • 2017-09-25
  • 2014-02-20
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
相关资源
最近更新 更多