ActiveRecords到JSON的数组

我知道ActiveRecord提供了一个to_json方法,它允许使用:only和:except从JSON输出中过滤掉字段。

目前我正在使用以下格式从find作为JSON格式化数组:

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

我如何能够在数组中的对象中选择要输出的字段? 有快捷方式还是需要手工完成?

干杯,亚当

如果要全局应用模型的更改,则可以覆盖模型类的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 

我想你回答了自己的问题。 使用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 

如果你窥视ActionController :: Base类,你会看到它立即调用你的集合中的to_json(没有使用额外的选项),所以你必须准备好它。 因此,如果在您的操作中您没有使用未呈现给json的属性,则可以将查找替换为

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

只选择你需要的那些。