2016-01-21 94 views
0

我有兩種模式:Cabinet和Workplace。Rails to_json belongs_to對象

class Cabinet < ActiveRecord::Base 

    def as_json(options={}) 
    options.merge!({except: [:created_at, :updated_at]}) 
    super(options) 
    end 

end 

class Workplace < ActiveRecord::Base 
    belongs_to :cabinet 

    def as_json(options = {}) 
    options.merge!(:except => [:created_at, :updated_at, :cabinet_id], include: :cabinet) 
    super(options) 
    end 

end 

當我打電話Cabinet.first.to_json我得到

{ 
    id: 1, 
    cabinet: "100" 
} 

,但是當我打電話Workplace.first.to_json ID獲得

{ 
    name: "first workplace", 
    Cabinet: { 
      id: 1, 
      cabinet: "100", 
      created_at: "#created_at", 
      updated_at: "#updated_at" 
      } 
} 

爲什麼呢?謝謝並對不起我的英語:)

回答

0

不知道我是否關注你,但是當你做Workplace.first.to_json時,你是否想從Workplace模型獲取屬性,而不是要獲取Cabinet數據?

我認爲這是因爲你在as_json方法配置中包含內閣,如here所解釋的。

您應該刪除或做:

Workplace.first.attributes.to_json 

讓我知道如果我缺少從你的問題的東西。

+0

對不起,我錯了把問題。我會得到內閣對象而不created_at和的updated_at字段:'''{ 名: 「第一工作場所」, 內閣:{ ID:1, 櫃: 「100」 } }''' – motoroller

0

我們假設您的模型Cabinet具有:id, :cabinet, :created_at, :updated_at屬性,而Workplace具有:id, :name, :cabinet_id, ....。現在

,如果你試圖解僱Cabinet.first.to_json着,當然它會呈現如下:

{ 
    id: 1, 
    cabinet: "100" 
} 

監守即屬性屬於Cabinet模型。然後,您還添加了這些代碼行options.merge!({except: [:created_at, :updated_at]}),這就是爲什麼它只呈現:id and :name屬性。如果你試圖解僱Workplace.first.to_json然後它會呈現:

{ 
    name: "first workplace", 
    Cabinet: { 
     id: 1, 
     cabinet: "100", 
     created_at: "#created_at", 
     updated_at: "#updated_at" 
     } 
} 

,因爲這些options.merge!(:except => [:created_at, :updated_at, :cabinet_id], include: :cabinet)的。你包括模型Cabinet,所以它會自動添加到你的JSON。

+0

我錯放這個問題。我重載Cabinet.as_json方法,但在此調用Workplace.first.to_json(包括::cabinet)未調用Cabinet.as_json和結果json對象包括created_at和updated_at字段。 – motoroller