简体   繁体   English

在rails活动记录中查询mysql

[英]Mysql query in rails active record

How would I convert this Mysql query to be run by rails active record? 如何将此Mysql查询转换为由rails活动记录运行?

SELECT * FROM opentimes WHERE id=1 AND open < NOW() AND closed > NOW();

Any help would be greatly appreciated thanks in advance. 任何帮助将非常感谢提前感谢。

OpenTimes.where(id: 1)
Assuming that you're following convention and ID is your primary key, you wouldn't need the second part of the query. 假设您遵循约定并且ID是您的主键,则不需要查询的第二部分。 Even then, here it is: 即便如此,这里是:
OpenTimes.where(id: 1, 'open < NOW() AND closed > NOW()')

Assuming your model name is OpenTime and columns are id, open and close. 假设您的模型名称是OpenTime且列是id,则打开和关闭。 The corresponding active record query for above sql will be: 以上sql的相应活动记录查询将是:

OpenTime.where("entity_id = ? AND created_at < ? AND updated_at > ?", 1, Time.now, Time.now)

Define a scope in your Opentime model: 在Opentime模型中定义范围:

class Opentime < ActiveRecord::Base
  ...
  scope :currently_open, -> { where('NOW() BETWEEN open AND closed') }
  ...
end

then you would use it like this: 然后你会像这样使用它:

Opentime.currently_open.where(id: 1)

ActiveRecord有find_by_sql方法,因此它可以简单地用作:

Opentime.find_by_sql("SELECT * FROM opentimes WHERE id=1 AND open < NOW() AND closed > NOW();")

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

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