Question

If I have a result from Activerecord I have a array of hashes, if I have eager loaded has_one associations each record hash has a nested hash of its associated record.

My question is, is there a quick rails method that allows you to merge these nested hashes into a single hash per record?

An analogy would be converting records and there associations into single table rows.

Another analogy would be a converting a hash of nested hashes at n levels into a single level hash.

Was it helpful?

Solution

Approach 1:

Include them in the select clause

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

Approach 2:

Use delegation

class Profile
  belongs_to :user
  # street1, street2, city etc
  delegate :name, :name=, :email, :email=, :to => :user  
end

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top