ActiveRecords数组到JSON [英] Array of ActiveRecords to JSON

查看:110
本文介绍了ActiveRecords数组到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道ActiveRecord提供了to_json方法,该方法允许使用:only和:except从JSON输出中过滤出字段.

I am aware that ActiveRecord provides a to_json method which allows fields to be filtered out of the JSON output using :only and :except.

目前,我正在使用以下格式将查找结果中的数组格式化为JSON:

At present I am using the following to format an array from a find as JSON:

@customers = Customer.find(:all)
...
format.js { render :json => @customers}

我如何能够选择要在数组对象中输出的字段?有快捷方式还是我需要手工完成?

How would I be able to select the fields to be output in the objects in the array? Is there a shortcut or do I need to do this by hand?

干杯, 亚当

推荐答案

如果要全局应用模型更改,则可以覆盖模型类的to_json方法.

You can overwrite the to_json method of the model class if you want to globally apply the change for the model.

例如,要从呈现的JSON中排除空值,您可以将原始ActiveRecord方法覆盖为_json

For example, to exclude null values from the rendered JSON you could overwrite the original ActiveRecord method to_json

  def to_json(options)
    hash = Serializer.new(self, options).serializable_record
    hash = { self.class.model_name => hash } if include_root_in_json
    ActiveSupport::JSON.encode(hash)
  end

在您的模型课程中使用它:

with this in your model class:

  def to_json(options)
    hash = Serializer.new(self, options).serializable_record.reject {|key, value| value.nil? }
    hash = { self.class.model_name => hash } if include_root_in_json
    ActiveSupport::JSON.encode(hash)
  end

这篇关于ActiveRecords数组到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆