如何在active_model_serializers中筛选UserType匹配的关联问题数据?
解决ActiveModelSerializer关联数据过滤问题
嘿,我来帮你搞定这个问题!你现在需要在返回Client的JSON响应时,只包含那些UserType和当前Client的UserType一致的Question记录,对吧?
方法一:在Serializer中直接过滤关联数据
你可以直接在ClientSerializer的has_many关联里添加过滤条件,不用修改模型代码:
class ClientSerializer < ActiveModel::Serializer attributes :id, :username, :access_token, :UserType has_many :questions do # 只返回和当前client的UserType匹配的questions object.questions.where(UserType: object.UserType) end end
方法二:在模型中定义复用的关联(推荐)
如果这个过滤逻辑在其他地方也会用到,更推荐在Client模型里定义一个带条件的关联,这样可以在多个地方复用:
首先修改Client模型:
# app/models/client.rb class Client < ApplicationRecord has_many :questions # 定义带过滤条件的关联 has_many :matching_user_type_questions, ->(client) { where(UserType: client.UserType) }, class_name: 'Question' end
然后在ClientSerializer中使用这个关联,并指定返回的key为questions,保持JSON结构不变:
class ClientSerializer < ActiveModel::Serializer attributes :id, :username, :access_token, :UserType has_many :matching_user_type_questions, key: :questions, include: :all end
效果验证
修改完成后,你的JSON响应就会自动过滤掉UserType不匹配的Question记录,和你期望的输出完全一致:
{ "id": 4, "username": "171fdkjgku", "access_token": "77NVccAJG7hEKSGQUcKkSip5", "UserType": 1, "questions": [ { "id": 1, "question": "Lorem Ipsum", "client_id": 4, "UserType": 1 }, { "id": 3, "question": "Lorem Ipsum 3", "client_id": 4, "UserType": 1 } ] }
内容的提问来源于stack exchange,提问作者Jasjeet Singh
相关产品推荐
相关产品推荐

