Sql Rails 4 where和select query with custom功能
我使用的是Rails 4,其表结构如下: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
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?
或选择查询应用查询链
x
是execution\u date:DateTime,那么f(x)可以是2^((execution\u date*1000)+200)
,只是一些复杂的函数(是的,它真的很复杂!!)。
所以,现在我们要基于复杂函数返回值(即DateTime)进行查询如果不知道如何使用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)
。