英文:
Convert a returning Hash of a Model's method to a serializable_hash (for as_json)
问题
你可以尝试在Controller中使用 as_json
方法,并结合 :only
和 :except
来过滤 child_data
方法返回的哈希数据,如下所示:
class Api::V5::Private::FamilyController < Api::V5::PrivateController
def index
families = Family.all.map do |family|
{
id: family.id,
last_name: family.last_name,
child_data: family.child_data.slice(:first_name, :gender)
}
end
render json: families
end
end
英文:
My Modelclass has a method, that returns some calculated data in form of a Hash. In the Controller I want to use this data, but want to include only some parts of the Hash.
My first idea was, to use the method inside :include
in the to_json-options instead of the :methods
field. But this will end in an undefined method 'serializable_hash'
-Error.
Model:
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
Controller:
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
How can I use the returning Hash of the method "child_data" inside to_json
/as_json
, but use :only
and :except
to filter the Hash?
答案1
得分: 0
以下是已翻译的部分:
- 使用一个具有方法 "serializable_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
- 在 "initializers/" 中重新打开 Ruby 的哈希类并添加方法:
config/initializers/hash_extensions.rb
class Hash
def serializable_hash opts
self.as_json(opts)
end
end
我将只返回翻译好的部分,不提供额外的内容。
英文:
Found two solutions for this:
- Use a module with method "serializable_hash" and extend the Hash with this module:
module Serializable
def serializable_hash opts
self.as_json(opts)
end
end
and
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
- Extend Ruby's Hash Class inside the "initializers/" by reopening the Class and add the method:
config/initializers/hash_extensions.rb
class Hash
def serializable_hash opts
self.as_json(opts)
end
end
I'll leave this here for anybody, who also got into this problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论