在rails活动记录中查询mysql

时间:2016-10-23 23:07:43

标签: mysql ruby-on-rails rails-activerecord

如何将此Mysql查询转换为由rails active record运行?

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

提前感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

OpenTimes.where(id: 1)
假设您遵循约定并且ID是您的主键,您将不需要查询的第二部分。即便如此,这里是:
OpenTimes.where(id: 1, 'open < NOW() AND closed > NOW()')

答案 1 :(得分:0)

假设您的模型名称为OpenTime且列为id,则打开和关闭。 上面sql的相应活动记录查询将是:

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

答案 2 :(得分:0)

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

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