Ruby on rails 协会';s属性作为模型';活动模型序列化程序中的s属性(无嵌套)

Ruby on rails 协会';s属性作为模型';活动模型序列化程序中的s属性(无嵌套),ruby-on-rails,ruby-on-rails-4,active-model-serializers,Ruby On Rails,Ruby On Rails 4,Active Model Serializers,我需要在活动模型序列化程序中的“属于”和“拥有”关联的属性前面加上关联名称,并将其序列化为模型的直接属性。我不想让它们嵌套, 在模型下,但将其平放在同一水平面上 比如说, class StudentSerializer attributes :name, :email belongs_to :school end class SchoolSerializer attributes :name, :location end 对于上述序列化程序,输出将是 { id: 1, n

我需要在活动模型序列化程序中的“属于”和“拥有”关联的属性前面加上关联名称,并将其序列化为模型的直接属性。我不想让它们嵌套, 在模型下,但将其平放在同一水平面上

比如说,

class StudentSerializer
  attributes :name, :email
  belongs_to :school
end

class SchoolSerializer
  attributes :name, :location
end
对于上述序列化程序,输出将是

{
  id: 1,
  name: 'John',
  email: 'mail@example.com',
  school: {
   id: 1,
   name: 'ABC School',
   location: 'US'
  }
}
但我需要它作为

{
  id: 1,
  name: 'John',
  email: 'mail@example.com',
  school_id: 1,
  school_name: 'ABC School',
  school_location: 'US'
}
我可以通过向序列化程序添加以下方法来实现这一点,如

attributes :school_id, :school_name, :school_location  

def school_name
  object.school.name
end

def school_location
  object.school.location
end
但我认为这不是一个“好”的解决方案,因为我需要为关联中的所有属性定义方法。有什么想法或解决方法(或者直接解决方案,如果我不知道的话)可以优雅地实现这一点吗?蒂亚

更新: 现在,我已经为每个关联临时使用了以下解决方法

attributes :school_name, :school_location

[:name, :location].each do |attr|
  define_method %(school_#{attr}) do
    object.school.send(attr)
  end
end

您可以将虚拟属性作为缺少的方法进行管理:

  attributes :school_id, :school_name, :school_location 

  def method_missing( name, *_args, &_block )
    method = name.to_s
    if method.start_with?( 'school_' )
      method.slice! 'school_'
      object.school.send( method )
    end
  end

  def respond_to_missing?( name, include_all = false )
    return true if name.to_s.start_with?( 'school_' )
    super
  end

谢谢@mat!我的一个朋友也提出了同样的想法,但是如果有更多的联想呢?比如说
属于:class
?我必须维护一个属于的数组,并有一个关联名,然后循环检查并返回值。流程变得复杂-(