2011-07-29 27 views

回答

4

您可以覆盖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 

用法:

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

将在什么地方clean_to_json.rb文件中最好放置在Rails的? – ethicalhack3r

+0

@ ethicalhack3r可能位于“lib”下,因为它扩展了默认功能并且不是特定于应用程序。 –

相关问题