Reputation: 1282
I'm trying to map an AR relation in a specific data structure (to be rendered as JSON) and I can't make it work, for some reason the relations are always nil
Client.includes(:fixed_odds_account, person: [:phones, :emails]).map do |client|
{
id: client.id,
uri: client.uri,
updated_at: client.updated_at,
balance: client.fixed_odds_account.current_balance,
email: client.person.emails.pluck(:address),
first_name: client.person.first_name,
last_name: client.person.last_name,
number: client.person.phones.pluck(:number)
}
I'd expect this to return an array of hashes, but it always fails on the "person" relationship, which is apparently nil (and it is not). What's weird is that if I remove the Hash and just puts client.person I can see my data. Any idea?
Upvotes: 1
Views: 100
Reputation: 3298
Use #joins
. With #includes
you might be hitting a Client without Person as it uses left outer join. You might also want to add #uniq
to remove duplicates.
Client.joins(:fixed_odds_account, person: [:phones, :emails]).uniq.map #code omitted
Upvotes: 2