How would I convert this Mysql query to be run by rails active record?
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. 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. The corresponding active record query for above sql will be:
OpenTime.where("entity_id = ? AND created_at < ? AND updated_at > ?", 1, Time.now, Time.now)
Define a scope in your Opentime model:
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();")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.