在ActiveRecord的to_json时跳过具有零值的属性 [英] Skip attributes having nil values when to_json on ActiveRecord

查看:99
本文介绍了在ActiveRecord的to_json时跳过具有零值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有什么办法可以跳过具有无属性 在ActiveRecord的to_json当值。 默认行为是包括零值:

i was wondering if there is any way to just skip attributes having nil values when to_json on ActiveRecord. The default behavior is to include a nil value:

有一个选项的方式,使这个值只是不会出现?

Is there an option way to make this value just not appear ?

推荐答案

@拉尔斯的答案将适用于一个单一的对象,但对于活动记录对象的数组,你将不得不遍历数组中的每个元素,并做转换。如果你想要这个转换每次你叫 .to_json 渲染:JSON => 为模型,您可以覆盖在这样的模型中的 as_json 功能:

@lars's answer will work for a single object, but for an array of Active Record objects, you will have to iterate through every element of the array and do the conversion. If you want this conversion everytime you call .to_json or render :json => for that model, you can override the as_json function in the model like this:

class Model
  ..
  def as_json(options={})
    super(options).reject { |k, v| v.nil? }
  end
end

另外,我假设你已经定义,的ActiveRecord :: Base.include_root_in_json = FALSE 在您的环境中(配置/初始化/ active_record。 RB 中的Rails 3和Rails的配置/初始化/ new_rails_defaults.rb 2)。否则,你将不得不实行@拉尔斯的功能全面的模型(以值[0] 获取属性哈希等)。

Also, I am assuming you have defined, ActiveRecord::Base.include_root_in_json = false in the your environment(config/initializers/active_record.rb in Rails 3 and config/initializers/new_rails_defaults.rb in Rails 2). Otherwise, you will have to implement @lars's function fully in the model(taking value[0] to get the attribute hash etc.).

只有当你想这样做,每次你调用使用此方法 .to_json 渲染:JSON => 相关型号。否则,你应该坚持@拉尔斯的答案。

Use this method only if you want to do this everytime you call .to_json or render :json => for that model. Otherwise you should stick to @lars's answer.

这篇关于在ActiveRecord的to_json时跳过具有零值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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