views:

401

answers:

3

Hi everyone!

I want to show in a view the tasks for a day in concrete (today). these tasks have an estimated time that must sum 6 hours per day.

in the model I have this method:

def self.tasks_for_today
  total_time = 0
  r = Array.new
  all(:conditions => "finished = 0").each do | t |
    total_time += t.estimated_time
    r << t if total_time <= 6
  end  
  r 
end

and works fine, but I need the "r" variable to be a instance of a Tasks model, not a instance of Array class...

How can I do that?

A: 

One refactor you might do already is to use a named_scoped for your unfinished tasks:

class Shirt < ActiveRecord::Base
  named_scope :unfinished, :conditions => {:finished => false}
end

You don't really want to return an instance (an instance means just one task).

You might be able to order your tasks, get a running sum, and then return only the tasks that have a running sum below 6. I have to think about it more, but if you do it that way, you'll end up using find_by_sql and SQL magic provided by your DB engine of choice.

Jon Smock
Hi, i want to select a set of tasks that together sum a total of 6 hours... the method that I write does that, but return an instance of Array and I need to be Activerecord, just like Model.all
Yeah, I was trying to use a named_scope somehow, because you can keep scoping it and use it just like ActiveRecord (ex. Tasks.unfinished.older_than(3.days))
Jon Smock
A: 

Your method will return an array of tasks and Task.all also returns an array of tasks. Try it:

>> Task.all.class
=> Array

And with any array you can do things like:

t.first
t.each {|a| ... }

What you exactly want to do with your result?

klew
A: 

Thanks guys, it was my mistake, the method does what I want...

Here is the final code:

def self.tasks_for_today
  total_time = 0
  r = Array.new
  all(:conditions => "finished = 0").each do | t |
    total_time += t.estimated_time
    total_time <= 6 ? r << t : break
  end
  r
end