开发者

showing only attributes that are not null in the Rails 3 as_json method

开发者 https://www.devze.com 2023-03-24 01:52 出处:网络
I\'m using the as_json method heavily in a couple of models 开发者_开发问答I have in a project I\'m working on, and what I\'m trying to do is to display those attributes on the fly ONLY if they are no

I'm using the as_json method heavily in a couple of models 开发者_开发问答I have in a project I'm working on, and what I'm trying to do is to display those attributes on the fly ONLY if they are not nil/Null ... does anyone have any idea how to go about this?


You can override as_json:

# clean_to_json.rb
module CleanToJson
  def as_json(options = nil)
    super(options).tap do |json|
      json.delete_if{|k,v| v.nil?}.as_json unless options.try(:delete, :null)
    end
  end
end

# foo.rb
class Foo < ActiveRecord::Base
  include CleanToJson
end

Usage:

@foo.as_json # Only present attributes
@foo.as_json(:null => true) # All attributes (former behavior)
0

精彩评论

暂无评论...
验证码 换一张
取 消