开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜