控制器从深层嵌套的关联中提取数据,其中bilancino belongs_to :operativo
依次为belongs_to :cdg
:
@cdgs = Cdg.order("id ASC").all
@bilancinos = Bilancino.joins(:operativo).order('cdg_id ASC').all
(其中有where子句)。
但是在渲染时
<% @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 %>
正在生成一个空数组,但如果在下面的
下面<% @bilancinos.each do |bilancino| %>
<%= bilancino.operativo.cdg.conto %> <%= bilancino.saldo %><br />
<% end %>
将呈现。因此,表达式@bilancinos.select{ |i| i.operativo.cdg_id
以某种方式缺少嵌套目标。
正确的语法是什么?
答案 0 :(得分:0)
我怀疑你的问题在这里:
@bilancinos.select{ |i| i.operativo.cdg_id == cdg }
例如,这是我在其中一个应用程序的控制台中看到的内容:
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>]
所以试试:
@bilancinos.select{ |i| i.operativo.cdg_id == cdg.id }