Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 重写JSON哈希_Ruby On Rails_Json_Ruby On Rails 4 - Fatal编程技术网

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