2016-02-25 62 views
0

假設我有一個模型User。每個用戶has_onepreferencehas_manycompanies列出模型的屬性,包括嵌套屬性

在「標準」嵌套屬性的形式,這種關係可能看起來像

{ 
    "name" => "Foo Bar", 
    "email" => "[email protected]", 
    "phone" => "555.555.5555", 
    "preference_attributes" => { 
    "daily_alerts" => true, 
    "time_zone" => "Pacific Time (US & Canada)" 
    }, 
    "companies_attributes" => { 
    "0" => { 
     "name" => "Shinra, Corp", 
     "location" => "Midgar" 
    }, 
    "1" => { 
     "name" => "Globo Gym", 
     "location" => "NYC" 
    } 
    } 
} 

如果我有這個散列(h),我可以很容易更新我的用戶屬性(假設我已經啓用accepts_nested_hashpreferencecompanies

@user.attributes = h 

但是我該怎麼做呢?我如何從@user開始並生成嵌套散列?簡單地做

@user.attributes 

只給出了User模特屬性,沒有嵌套preferencecompanies性能。

謝謝!

回答

1

這可能很笨重,但會形成一個散列值@user屬性/值加上關聯關係及其屬性/值。

hash = @user.attributes.to_h 
associations = User.reflect_on_all_associations.map(&:name) 

associations.each do |association| 
    hash[association.to_s] = @user.send(association).map(&:attributes) 
end 

hash 
+0

謝謝!類似的東西應該可以工作,但希望有一種更習慣或內在的方式來檢索它。 – user2490003

+0

我認爲沒有。雖然我很想被證明是錯誤的 – MilesStanfield