简体   繁体   English

数组到活动记录 Model

[英]Array to Active Record Model

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.这些任务的估计时间必须每天加起来 6 小时。

in the model I have this method:在 model 我有这个方法:

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...并且工作正常,但我需要“r”变量是任务 model 的实例,而不是数组 class 的实例......

How can I do that?我怎样才能做到这一点?

One refactor you might do already is to use a named_scoped for your unfinished tasks:您可能已经做过的一项重构是对未完成的任务使用named_scoped

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.您也许可以对任务进行排序,获取运行总和,然后仅返回运行总和低于 6 的任务。我必须考虑更多,但如果您这样做,最终将使用find_by_sql和 SQL 魔术由您选择的数据库引擎提供。

Your method will return an array of tasks and Task.all also returns an array of tasks.您的方法将返回一个任务数组,而 Task.all 也会返回一个任务数组。 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?你到底想用你的结果做什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM