【问题标题】:Limiting Associations Cascade in Active Model Serializer在活动模型序列化器中限制关联级联
【发布时间】:2013-05-01 02:38:59
【问题描述】:

我在限制活动模型资源中序列化的关联级别时遇到问题。

例如:

一个游戏有很多团队,有很多玩家

class GameSerializer < ActiveModel::Serializer
  attributes :id
  has_many :teams
end

class TeamSerializer < ActiveModel::Serializer
  attributes :id
  has_many :players
end

class PlayerSerializer < ActiveModel::Serializer
  attributes :id, :name
end

当我检索团队的 JSON 时,它会根据需要将所有玩家包含在一个子数组中。

当我检索游戏的 JSON 时,它包含子数组中的所有团队,非常棒,而且还包含每个团队的所有玩家。这是预期的行为,但是否可以限制关联级别?游戏是否只​​返回没有玩家的序列化团队?

【问题讨论】:

    标签: ruby-on-rails-3 active-model-serializers


    【解决方案1】:

    另一种选择是滥用 Rails 的预加载来确定要渲染的关联:

    在您的 Rails 控制器中:

    def show
      @post = Post.includes(:comments).find(params[:id])
      render json: @post
    end
    

    然后在 AMS 土地上:

    class PostSerializer < ActiveModel::Serializer
      attributes :id, :title
      has_many :comments, embed: :id, serializer: CommentSerializer, include: true
    
      def include_comments?
        # would include because the association is hydrated
        object.association(:comments).loaded?
      end
    end
    

    可能不是最干净的解决方案,但对我来说效果很好!

    【讨论】:

    • object.association(:comments).loaded? 这正是我想要的,谢谢!我认为这种方法比公认的答案更干净。从 active_model_serializer 文档中,它建议使用连接或包含在控制器中包含关联以避免 n+1 查询。我被难住的地方是在序列化程序中如何确定关联是否已加载或省略。来自文档:“通过确保以最佳方式加载数据来避免 n+1 查询,例如,如果您使用 ActiveRecord,您可能希望根据需要使用查询包含或连接”
    • 我必须在哪里调用 include_cmets?方法?
    【解决方案2】:

    您可以创建另一个Serializer

    class ShortTeamSerializer < ActiveModel::Serializer
      attributes :id
    end
    

    然后:

    class GameSerializer < ActiveModel::Serializer
      attributes :id
      has_many :teams, serializer: ShortTeamSerializer
    end
    

    或者你可以在GameSerializer中定义一个include_teams?

    class GameSerializer < ActiveModel::Serializer
      attributes :id
      has_many :teams
    
      def include_teams?
        @options[:include_teams]
      end
    end
    

    【讨论】:

    • 感谢 Pablo,这就是我最终要做的事情......我试着让它有点轨道式,建模 :index 和 :show 复数,但有一个 TeamsSerializerTeamSerializer。特殊情况使用不同的序列化程序。
    • @options 是从哪里来的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    相关资源
    最近更新 更多