On 16 March 2010 15:33, Clay H. <[email protected]> wrote:
> On Mar 16, 8:33 am, Michael Pavling <[email protected]> wrote:
>>
>> And post again if you need any more help.
>
> Hey, thanks for the help so far. I went with a method in the
> Medicine.rb model file and I'm trying to display the results through
> the view, using code similar to what you suggested. I modified the
> code to appear as follows for now:
No worries (although if you're *not* working for a charity in Haiti
there's gonna be hell to pay!)
> def grouped_stocks
> stocks.group_by{|s| [s.route.name, s.strength]}
> end
>
> The result is an ordered hash, correct? Here's some really ugly code
> in the view:
<snipped extremely ugly code>
You *can* do it by chopping up the key, but essentially you could't
care less about the key - it's just a method of grouping all the items
together how we want.
If you iterate down to the individual stocks arrayed inside the hash,
you should have access to everything you need from there:
<%
@medicine.grouped_stocks.each_pair do |k, v|
v.each do |stock|
%>
<%= "#{stock.medicine.name} #{stock.strength} #{stock.route.name}" %>
<%
end
end
%>
> Also, is it possible to order the hash so that they appear in
> descending order of how much of each item is in stock? In other words,
> sort descending by the value that the following generates?
>
> <%=h "#{s.last.sum(&:amount_received) -
> s.last.sum(&:amount_dispensed)}" %>
Good god man! :-)
erm... off the top of my head I don't know (as I hadn't played with
group_by until last night). Whether the .sort method works on the
OrderedHash (the API is eluding me at the moment), or whether you'd
need to extract the keys and totals to an array of arrays and sort
that by totals (so then rather than iterating grouped_stocks, you
access it by key taken from the sorted array), I don't know which...
Re-reading it: Does that make any sense?!
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.