On 16 March 2010 12:03, Clay H. <[email protected]> wrote:
> On Mar 15, 9:25 pm, Michael Pavling <[email protected]> wrote:
>> Using Enumerable.group_by:
>>
>> Stock.all.group_by{|s| [s.medicine.name, s.route.name, s.strength]}.each do 
>> |s|
>>   puts "#{s.first.inspect} #{s.last.sum(&:amount_received) -
>> s.last.sum(&:amount_dispensed)}"
>> end
>>
>> Does that give you enough to work with?
>
> I think so. I can create a method in the Medicine model that includes
> this code and then call that method on each med on the the show and/or
> index views, right?

In the Medicine model it might work like this:
def grouped_stocks
  stocks.group_by{|s| [s.medicine.name, s.route.name, s.strength]}
end

then in the view you can play with the iteration:

<% @medicine.grouped_stocks.each do |s| %>
  <%= "#{s.first.inspect} #{s.last.sum(&:amount_received) -
s.last.sum(&:amount_dispensed)}" %>
<% end %>
(... totally untested I'm afraid)

> If I go with the SQL you suggested above, where would I use that? Also
> in a method in the Model?

That would more likely be better used to populate a variable in the
controller that's passed to the view... it's not a very nice method of
getting data in Rails (ignoring the DB abstraction!), but it's easy to
tweak (add WHERE clauses to restrict by medicine, etc) and iterate
through for quick results.

Play with them both in an IRB console (and your DB management tool) -
that's what I did to get close to what I thought might do the job.

And post again if you need any more help.

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