2011-07-29 25 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」下,因爲它擴展了默認功能並且不是特定於應用程序。 –

相關問題