2009-06-19 26 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