2009-06-19 72 views
2

我知道ActiveRecord提供了一个to_json方法,它允许使用以下字段将字段过滤出JSON输出:only和:except。ActiveRecords到JSON的数组

目前我使用下面从发现作为JSON格式的数组:

@customers = Customer.find(:all) 
... 
format.js { render :json => @customers} 

我将如何能够选择区域是在数组中的对象输出?有没有捷径,还是我需要手动做这个?

干杯, 亚当

回答

2

如果要全局应用模型的更改,则可以覆盖模型类的to_json方法。

例如,从呈现的JSON排除空值,你可以覆盖原来的ActiveRecord方法to_json

def to_json(options) 
    hash = Serializer.new(self, options).serializable_record 
    hash = { self.class.model_name => hash } if include_root_in_json 
    ActiveSupport::JSON.encode(hash) 
    end 

与此模型中的类:

def to_json(options) 
    hash = Serializer.new(self, options).serializable_record.reject {|key, value| value.nil? } 
    hash = { self.class.model_name => hash } if include_root_in_json 
    ActiveSupport::JSON.encode(hash) 
    end 
1

如果你窥视到的ActionController :: Base类,你会发现它在你的收集调用to_json立即(不使用额外的选项),所以你一定要拥有它已经准备好。所以,如果你的动作你不使用未呈现为JSON的属性,你可以用

@customers = Customer.find(:all, :select => ["id", ...]) 

更换您发现只有选择你需要的人。

2

我想你回答了你自己题。使用Rails 2.3.x,您可以使用以下内容:

@customers = Customer.all #Shortcut for to Customer.find(:all) 
respond_to do |format| 
    format.js { render :json => @customers.to_json(:only=>[:column_one, :column_two]} 
end