【问题标题】:Override JSON hash覆盖 JSON 哈希
【发布时间】:2015-06-11 08:22:40
【问题描述】:

这里是上下文:我有一个模型和一个控制器,像这样(非常简化,仅用于示例):

class Model < ActiveRecord::Base
  def to_json(options = {})
    return super({ :except => [ :id ] })
  end
end

class ModelsController < ApplicationController
  def show
    return @contact.to_json
  end
  def some_action
    return { "foo" => @contact }.to_json
  end
end

当我调用 show 动作时,Modelto_json 动作被调用,并且我有一个没有 id 的 json:

 {"first_name":"Vincent",[...]}

当我调用some_action 操作时,结果如下所示:

 {"foo": "<Model:0x000000048c7388>"}

怎么会有这样的反应?

 {"foo": {"first_name":"Vincent",[...]}}

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-4


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      我建议使用诸如ActiveModel::Serializers 之类的序列化程序库。

      gem 'active_model_serializers', '~> 0.9.3'
      

      注意版本!然后创建一个包含

      /app/serializers/contact_serializer.rb
      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": "..."}}
      

      【讨论】:

        【解决方案3】:

        在这种情况下,最好的方法是在模型中重新定义 serializable_hash,这样使用 as_json 方法会返回一个 json,其中定义在 serialazable_hash 方法中。像这样的:

          class Model < ActiveRecord::Base
            def serialazable_hash(options = {})
                options ||= {}
                options = {
                  except: [:id]
                }.update(options)
                super options
            end
          end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-17
          • 1970-01-01
          • 2017-05-02
          • 1970-01-01
          • 2019-10-04
          • 2019-03-21
          • 1970-01-01
          • 2020-07-25
          相关资源
          最近更新 更多