mapping values through deeply nested associations

53 Views Asked by At

A controller extracts data from deeply nested associations where bilancino belongs_to :operativo which in turn belongs_to :cdg as such:

@cdgs = Cdg.order("id ASC").all
@bilancinos = Bilancino.joins(:operativo).order('cdg_id ASC').all

(with a where clause in there).

However when rendering

<% @cdgs.each do |cdg| %>
  <% @cdgs_for_bilancino = @bilancinos.select{ |i| i.operativo.cdg_id == cdg } %>
  <%= @cdgs_for_bilancino.each do |bilancino| %> XX <% end %>
  <%= number_with_precision(@cdgs_for_bilancino.map(&:saldo).sum, :precision => 0, :delimiter => "\u00a0")  %>
<% end %>

is generating an empty array, yet if underneath the following

<% @bilancinos.each do |bilancino| %>
  <%= bilancino.operativo.cdg.conto %> <%= bilancino.saldo %><br />
<% end %>

will render. Thus the expression @bilancinos.select{ |i| i.operativo.cdg_id is missing the nested target somehow.

What is the proper syntax?

1

There are 1 best solutions below

1
klenwell On

I suspect your issue is here:

@bilancinos.select{ |i| i.operativo.cdg_id == cdg }

For example, this is what I see in the console of one of my apps:

irb(main):022:0> recruiter = Recruiter.find_by_id(1)
  Recruiter Load (0.9ms)  SELECT  "recruiters".* FROM "recruiters" WHERE "recruiters"."id" = $1 LIMIT 1  [["id", 1]]
=> #<Recruiter id: 1>
irb(main):023:0> ping = Ping.find_by_id(1)
  Ping Load (0.9ms)  SELECT  "pings".* FROM "pings" WHERE "pings"."id" = $1 LIMIT 1  [["id", 1]]
=> #<Ping id: 1, recruiter_id: 1>
irb(main):024:0> recruiter.pings.select{ |p| p.id == ping }
  Ping Load (0.5ms)  SELECT "pings".* FROM "pings" WHERE "pings"."recruiter_id" = $1  [["recruiter_id", 1]]
=> []
irb(main):025:0> recruiter.pings.select{ |p| p.id == ping.id }
=> [#<Ping id: 1, recruiter_id: 1>]

So try:

@bilancinos.select{ |i| i.operativo.cdg_id == cdg.id }