【问题标题】:Rails - Dinamically select attributes to be serializedRails - 动态选择要序列化的属性
【发布时间】:2017-11-04 12:24:30
【问题描述】:

我正在使用 ActiveModel 序列化器来序列化我的模型,并且我经常需要创建一个新的序列化器以满足控制器的需求,而不会将不必要的信息包含到另一个控制器中。

class ContactGroupSerializer < ActiveModel::Serializer
  attributes :id, :name, :contacts, :contacts_count, 
             :company_id, :user_id

  def contacts_count
    object.contacts.count
  end
end

有没有办法定义一个序列化器,例如上面的那个,它们动态地选择要包含在我的控制器响应中的属性?

class ContactsGroupsController < ApplicationController
  def index
    ...
    render json: @contact_groups // here I would like to return only id and name, for example
  end
end

我知道我可以通过创建另一个序列化程序来实现,但我不想这样做。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 serialization


【解决方案1】:

好吧,您可以在 application_controller.rb 中定义一个方法,您可以将所有要渲染的对象传递给该方法,并使用要作为响应返回的方法数组来呈现......例如,

def response_for(object, methods = [:id])
  if object.blank?
    head :no_content
  elsif object.errors.any?
    render json: { errors: object.errors.messages }, status: 422
  else
    render json: build_hash_for(object, methods), status: 200
  end
end

private #or in your `application_helper.rb`

def build_hash_for(object, methods)
  methods.inject({}) do |hash, method|
    hash.merge!(method => object.send(method))
  end
end

在上述特定情况下,您可以

class ContactsGroupsController < ApplicationController

  def index
    ...
    response_for @contact_groups, [:id, :name]
  end
end

【讨论】:

  • 谢谢,这是一个有趣的方法。问题是我仍然希望能够定义仅在序列化程序上可用的“虚拟”属性,例如 contacts_count 属性。所以这个想法是为每个模型仍然有一个序列化器。问题是同一模型有很多序列化器。
猜你喜欢
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多