I have a model ExchangeRates
which has a field time
of type DateTime
. I want to search for an exchange rate from the same day. I tried in the following manner:
per = ExchangeRates.find_by(time: er.time.beginning_of_day..er.time.end_of_day)
However, this doesn't return an ExchangeRate object from the same day. How could I correct this?
You may be better served attempting this with a where
as follows:
per = ExchangeRates.where("time > ? AND time < ?", er.time.beginning_of_day, er.time.end_of_day)
This will translate your request directly into the SQL. While it's much less ActiveRecord "ish" than I prefer, I've found no good way to do something simple that searches for ranges.
If you want something even cleaner you could consider monkey patching AR to support a range
operation that effectively does something like this under the hood with the passed in hash.
This should work for you
per = ExchangeRates.where(time: er.time.beginning_of_day..er.time.end_of_day).first
However, when i frequently use this type of query on a model, i prefer to duplicate data, and also use a date column.
Lets say, if i have a created_at column, i also add a created_on column. One has datetime type, letter has date type.
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.