2016-02-25 126 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