Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Rails 4 where和select query with custom功能_Sql_Ruby On Rails_Ruby_Postgresql_Ruby On Rails 4 - Fatal编程技术网

Sql Rails 4 where和select query with custom功能

Sql Rails 4 where和select query with custom功能,sql,ruby-on-rails,ruby,postgresql,ruby-on-rails-4,Sql,Ruby On Rails,Ruby,Postgresql,Ruby On Rails 4,我使用的是Rails 4,其表结构如下: Order(id: integer, ..., created_at: datetime, states_time: string) 现在我想根据states_time,forex查询上表:以查找在时间t1和t2之间调度的所有订单。给定的调度时间可以使用函数get\u dispatch\u time(x)计算 希望最终where查询应该是这样的: Order.all.where(get_dipatch_time: t1..t2) # WRONG SYN

我使用的是Rails 4,其表结构如下:

Order(id: integer, ..., created_at: datetime, states_time: string)
现在我想根据states_time,forex查询上表:以查找在时间t1和t2之间调度的所有订单。给定的调度时间可以使用函数
get\u dispatch\u time(x)
计算

希望最终where查询应该是这样的:

Order.all.where(get_dipatch_time: t1..t2) # WRONG SYNTAX
类似于:

Order.all.where(created_at: t1..t2)
我可以使用
select
query和lamda表达式获取此数据,但问题是它将返回ActiveRecord对象数组,而不是ActiveRecord::Relation,因此无法对其执行进一步的查询(分页查询)

Order.all.select{ |o| get_dispatch_time(o) > t1 && get_dispatch_time(o) < t2 }
=> #[#<Order id: 10, ship_by: ....>, #<Order id: 2, ..> ]
Order.all.选择{o|get|u dispatch_time(o)>t1&&get|u dispatch_time(o) #[#, # ]
但是,要求的结果应该是:

=> #<ActiveRecord::Relation [#<Order id: 10, ship_by: ....>, #<Order id: 2, ..> ]>
=>#
主要问题是只能通过ActiveRecord::Relation链接查询。外汇:
Order.where(…).Order(…).sort(…).limit(…)

有人能帮我吗

  • 如何将自定义方法用于
    where
    query,返回ActiveRecord::Relation?
  • 如何使用
    选择
    查询应用查询链
  • 编辑

    一些澄清:

  • get_dispatch_time(x)是一个Ruby函数

  • 我需要根据一些自定义函数f(x)过滤数据,其中x是列名。外汇:如果列名
    x
    是execution\u date:DateTime,那么f(x)可以是
    2^((execution\u date*1000)+200)
    ,只是一些复杂的函数(是的,它真的很复杂!!)。 所以,现在我们要基于复杂函数返回值(即DateTime)进行查询

  • 对列名进行查询很容易,我的问题是如何对自定义函数进行查询。(如上所述,使用lambda表达式进行select查询是可能的。但是where查询也可能吗?有没有其他方法可以解决上述问题?)


  • 如果不知道如何使用sql函数,则不需要它

    外汇:查找在时间t1和t2之间发送的所有订单

    例如,您有一个model
    Foo
    ,列为
    execution\u date:date
    。要在
    foos
    表中查找执行日期在
    t1
    t2
    范围内的所有记录,必须使用下一个查询:

    Foo.where('execution_date > ? OR execution date < ?', t1, t2)
    
    Foo.where('execution_date>?或execution date<?',t1,t2)
    

    此查询表示“我正在查找foos表中执行日期大于t1或小于t2的记录”

    get\u dispatch\u time函数的作用是什么?你能模拟一下它在SQL中的行为吗?
    get\u dispatch\u time
    是SQL函数还是Ruby函数?你能把它包括在问题中吗?
    get\u dispatch\u time
    是一个Ruby函数(基本概述:它迭代一个JSON字符串(多次字符串化),并在历元字符串中获取适当的时间,然后将其作为DateTime返回)。我编辑了这篇文章以使其更加清晰。对列名触发查询很容易。问题在于,如果execution\u date是列,则在自定义函数上触发它,比如
    函数(Foo.execution\u date)