简体   繁体   中英

Use active record to find a record by month and day, ignoring year and time

I have a model (Entries) with five years worth of records (one record per day). I need a method that, when passed a date object such as 2011-12-25 00:00:00 , will show me ALL the records that have happened on 12/25 (querying against the :created_at column), regardless of the year or time that's passed.

RoR 3.0.9 / Ruby 1.9.2p290

You can use the MONTH and DAY values of mysql. Maybe something like:

Model.where("MONTH(created_at) = ? and DAY(created_at) = ?", somedate.month, somedate.day)

A general solution that should work with most SQL databases (include MySQL and PostgreSQL):

Entry.where('extract(month from created_at) = ? AND extract(day from created_at) = ?', d.month, d.day)

SQLite doesn't understand extract though so you'd have to use:

Entry.where("strftime('%m/%d', created_at) = ?", d.strftime('%m/%d'))

假设您使用的是mysql:

User.where(["DAY(created_at) = ? AND MONTH(created_at) = ?", date.day, date.month])

Assume RDBMS is MySQL and you have form with combobox to select month and/or date_of_months, may be you could make a named_scope, for example :

scope :by_date_or_month, lambda { |date, month| {:conditions => ["DAYOFMONTH(created_at) = ? or MONTH(created_at) = ?", date, month]}}

Test from IRB :

Model.by_date_or_month(31,8)
Model.by_date_or_month(nil,8)

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.

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