0

如果我有来自 Activerecord 的结果,我有一个散列数组,如果我已经预先加载了 has_one 关联,则每个记录散列都有其关联记录的嵌套散列。

我的问题是,是否有一种快速的 rails 方法可以让您将这些嵌套的哈希合并到每条记录的单个哈希中?

一个类比是将记录和关联转换为单个表行。

另一个类比是将 n 级嵌套散列的散列转换为单级散列。

4

2 回答 2

1

方法一:

将它们包含在 select 子句中

class User
  has_one :profile
end

class Profile
  belongs_to :user
  # street1, street2, city etc
end

profiles = Profile.joins(:user).select("users.*, profiles.*").all
profiles.first.login

方法二:

使用委托

class Profile
  belongs_to :user
  # street1, street2, city etc
  delegate :name, :name=, :email, :email=, :to => :user  
end
于 2011-09-02T18:22:12.700 回答
0

扁平化方法呢? http://www.ruby-doc.org/core/classes/Array.html#M000280

于 2011-09-02T18:14:10.087 回答