2010-03-31 50 views
5

我想在AR模型調用to_json時修改類名。覆蓋as_json或to_json模型類名

Book.first.to_json 
#=> "{\"book\":{\"created_at\":\"2010-03-23 

Book.first.to_json(:root => 'libro') 
#=> "{\"libro\":{\"created_at\":\"2010-03-23 

有一個選項來做到這一點?

+1

我不知道有關重寫to_json但您可以設置的ActiveRecord :: Base.include_root_in_json =假,也不會輸出根節點,然後你可以添加無論你喜歡什麼根節點。 – Corey 2010-03-31 22:04:37

回答

0

您可以覆蓋模型中的默認to_json方法,建立你想要的屬性的哈希值,然後調用散列的to_json方法。

class Book < ActiveRecord::Base 

    def to_json 
    { :libro => { :created_at => created_at } }.to_json 
    end 

end 

#=> "{\"libro\":{\"created_at\":\"2010-03-26T13:45:28Z\"}}" 

或者,如果你希望所有的記錄屬性...

def to_json 
    { :libro => self.attributes }.to_json 
end 
28

要使用Rails 3兼容,覆蓋的as_json代替to_json。它在2.3.3中引入:

def as_json(options={}) 
    { :libro => { :created_at => created_at } } 
end 

確保ActiveRecord::Base.include_root_in_json = false。當你調用to_json,幕後as_json背後是用來建立數據結構,並ActiveSupport::json.encode用於將數據編碼成JSON字符串。

6

由於3.0.5,至少,你現在有一個傳遞的選項:root選項的to_json通話。以下是現在活動記錄中as_json方法的來源。

def as_json(options = nil) 
    hash = serializable_hash(options) 

    if include_root_in_json 
     custom_root = options && options[:root] 
     hash = { custom_root || self.class.model_name.element => hash } 
    end 

    hash 
end 

所以使用這只是@obj.to_json(:root => 'custom_obj')