Ruby on rails 重写JSON哈希
以下是上下文:我有一个模型和一个控制器,如下所示(非常简单,仅作为示例): 当我调用Ruby on rails 重写JSON哈希,ruby-on-rails,json,ruby-on-rails-4,Ruby On Rails,Json,Ruby On Rails 4,以下是上下文:我有一个模型和一个控制器,如下所示(非常简单,仅作为示例): 当我调用some_action操作时,结果如下所示: {"foo": "<Model:0x000000048c7388>"} 将用作\u json而不是用于\u json 我建议使用序列化程序库,如 注意版本然后创建一个包含 class ContactSerializer < ActiveModel::Serializer attributes :first_name end 在这种情况下,最
some_action
操作时,结果如下所示:
{"foo": "<Model:0x000000048c7388>"}
将
用作\u json
而不是用于\u json
我建议使用序列化程序库,如 注意版本然后创建一个包含
class ContactSerializer < ActiveModel::Serializer
attributes :first_name
end
在这种情况下,最好的方法是在模型中重新定义serializable_散列,这种方法使用as_json方法,它将返回一个json,其中包含serializable_散列方法中的定义。大概是这样的:
class Model < ActiveRecord::Base
def serialazable_hash(options = {})
options ||= {}
options = {
except: [:id]
}.update(options)
super options
end
end
类模型
{"foo": {"first_name":"Vincent",[...]}}
gem 'active_model_serializers', '~> 0.9.3'
class ContactSerializer < ActiveModel::Serializer
attributes :first_name
end
class ContactsController < ApplicationController
def show
render json: @contact, root: false
end
def some_action
render json: @contact, root: 'foo'
end
end
# show
{"first_name": "..."}
# some_action
{"foo": {"first_name": "..."}}
class Model < ActiveRecord::Base
def serialazable_hash(options = {})
options ||= {}
options = {
except: [:id]
}.update(options)
super options
end
end