Convert a Activerecord result with has_one associations into a single hash per record
-
19-01-2021 - |
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.
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
What about the flatten method? http://www.ruby-doc.org/core/classes/Array.html#M000280
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow