简体   繁体   English

Rails 5.1 .:从关联中获取每个日期时间间隔的记录

[英]Rails 5.1.: get records from association for each datetime interval

I have Model named Task with method dates which gives me this output (it can be different and multiple DateTime intervals): 我有一个名为Task模型,带有方法dates ,这给了我这个输出(可以不同,可以有多个DateTime间隔):

[{:from=>2017-09-04 00:00:00 +0300, :to=>2017-09-04 05:59:59 +0300},
 {:from=>2017-09-05 12:00:00 +0300, :to=>2017-09-05 19:59:59 +0300}

then in same Model there is another method inventory , where for each task I want to get corresponding Inventory model records. 然后在同一模型中,还有另一种方法inventory ,对于每个task我想获得相应的Inventory模型记录。

At the moment I'm trying to do something like this: 目前,我正在尝试执行以下操作:

self.inventories.where(date: self.from..self.to)

This does not work, because from and to comes from data structure above and there are no such columns in my DB. 这是行不通的,因为fromto来自上面的数据结构,并且我的数据库中没有这样的列。 I've set appropriate association in my model and I can do self.inventories . 我已经在模型中设置了适当的关联,并且可以进行self.inventories

Is there a way to do Rails query in order to grab matching records for each of my dates intervals, please? 有没有一种方法可以进行Rails查询,以便获取每个dates间隔的匹配记录? Thank you. 谢谢。

if your asking how to access data inside an array, you can loop through each data. 如果您询问如何访问数组内的数据,则可以遍历每个数据。

def self.dates
  #generate intervals as array of hashes
end

def self.inventories
  [].tap do |inventories|
    dates.each do |date|
      from = date[:from]
      to = date[:to]
      inventories << self.inventories.where(date: from..to)
    end
  end
end

and ensure to use #flatten since it would be nested in arrays 并确保使用#flatten,因为它将嵌套在数组中

inventories.flatten inventories.flatten

hope this helps 希望这可以帮助

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

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