Cycling through array of objects within view in Rails: unexpected behaviour
-
20-08-2019 - |
Question
I've got a simple calendar displaying some events, that's not quite giving me the expected results. Here's the code:
<!-- Begin Calendar -->
<%= calendar(:year => @year, :month => @month, :first_day_of_week => 1) do |d|
output = []
output << render_calendar_cell(d.mday)
if d.wday == 1
@garden.plants.collect do |p|
if p.needs_sowing? (d.cweek)
output << "This week sow: #{p.name}"
end
end
end
end
%>
<!-- end calendar-->
here's the need_sowing? method called within the block:
def needs_sowing? (week)
if !sow_out_week_min.blank? && !sow_out_week_max.blank?
(sow_out_week_min..sow_out_week_max).include? (week)
end
end
This is giving me the correct behaviour when there is only one plant being inspected in the loop, but if there are more than one, then no output will be displayed apart from the initial
output << render_calendar_cell(d.mday)
(which just outputs the day of the month).
Can anyone lend a hand to let me know where I'm maybe going wrong? Or got some tips on a better way to process this kind of behaviour in the loop?
TIA
Solution
You should be using @garden.plants.each
instead of collect
. Collect should be used to filter array results not to loop over them.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow