On 17 March 2010 13:33, Clay H. <[email protected]> wrote:
> the only issue is that amount_on_hand is a method
> in the Medicine model, not in the Stock model -- it performs an
> aggregate sum for all of the stocks belonging to the medicine in
> question. This code uses it as a Stock method, doesn't it?

Of course - so that's a pain...

Well, there's always the approach of extracting the keys, sorting
them, and then accessing the grouped_stocks by key:

# Medicine model
  def grouped_stocks_keys_ordered_by_amount_on_hand
    grouped_stocks.map {|gs| [gs.first,
(gs.last.sum(&:amount_received) -
gs.last.sum(&:amount_dispensed))]}.sort_by {|grouping|
grouping[1]}.map {|key_pair| key_pair[0]}
  end

#IRB
>> Medicine.first.grouped_stocks_keys_ordered_by_amount_on_hand.each do |key|
?> puts "STOCK FOR #{key.inspect}"
>> puts m.grouped_stocks[key].inspect
>> end

This should loop through the keys and pull out the grouped_stocks
value for that key. To save building the hash of grouped_stocks for
every iteration through the keys, you can memoize it:

  def grouped_stocks
    @grouped_stocks ||= stocks.group_by{|s| [s.route.name, s.strength]}
  end

I hope you can see that you can alter the IRB example to use in your
view to draw a table (or whatever) for the data in the order you want.

The "grouped_stocks_keys..." method can probably be made more
efficient (and certainly more legible!) with some refactoring (a few
applications of Extract Method would make it clearer), but I like to
get stuff working first and streamline after.

-- 
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.

Reply via email to