列出模型的属性,包括嵌套属性

时间:2016-02-25 00:38:40

标签: ruby-on-rails activerecord

我们说我有一个模型User。每位用户has_one preferencehas_many companies

"标准"嵌套属性表单,这种关系可能看起来像

{
  "name" => "Foo Bar",
  "email" => "foo.bar@example.co",
  "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_hash和{{1}启用了preference }})

companies

但我该怎么办呢?如何从@user.attributes = h 开始并生成嵌套哈希?只是做

@user

仅提供@user.attributes 模型属性,不包含嵌套的Userpreference属性。

谢谢!

1 个答案:

答案 0 :(得分: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