ruby 将Model方法的返回Hash转换为serializable_hash(对于as_json)

xt0899hw  于 2023-06-29  发布在  Ruby
关注(0)|答案(1)|浏览(105)

我的Modelclass有一个方法,它以Hash的形式返回一些计算数据。在控制器中,我想使用这些数据,但只想包含哈希的一部分。
我的第一个想法是,在to_json-options中使用:include内部的方法,而不是:methods字段。但这将以undefined method 'serializable_hash'-Error结束。
型号:

class Family < ActiveRecord::Base

  def child_data
    {
      gender: self.child_gender,
      first_name: self.child_first_name,
      last_name: self.child_last_name,
      email: self.child_email,
      phone: self.child_phone
    }
  end

end

控制器:

class Api::V5::Private::FamilyController < Api::V5::PrivateController

  def index

    render json: Family.all.to_json({
      only: [ :id, :last_name ],
      # methods: [ :child_data ], <-- WOULD WORK
      include: {
        child_data: {
          only: [ :first_name, :gender ]
        }
      }
    })

  end

end

如何在to_json/as_json中使用方法“child_data”的返回Hash,但使用:only:except来过滤Hash?

wd2eg0qa

wd2eg0qa1#

找到了两个解决方案:
1.使用一个带有“serializable_hash”方法的模块,并使用这个模块扩展Hash:

module Serializable
  
  def serializable_hash opts
    self.as_json(opts)
  end
  
end

def child_data
   {
      gender: self.child_gender,
      first_name: self.child_first_name,
      last_name: self.child_last_name,
      email: self.child_email,
      phone: self.child_phone

   }.extend(Serializable)
end

1.在“initializers/”中扩展Ruby的Hash Class,方法是重新打开Class并添加方法:

  • config/initializers/hash_extensions.rb*
class Hash
  def serializable_hash opts
    self.as_json(opts)
  end
end

我会把这个留给任何人,谁也陷入了这个问题。

相关问题