ActiveRecords到JSON的数组

时间:2009-06-19 11:09:20

标签: ruby-on-rails json

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

目前我正在使用以下内容将find中的数组格式化为JSON:

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

如何选择要在数组中的对象中输出的字段?是否有快捷方式,或者我需要手动执行此操作?

干杯, 亚当

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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

答案 2 :(得分:1)

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

替换您的查找
@customers = Customer.find(:all, :select => ["id", ...])

只选择你需要的那些。