Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Rails中,当使用“where”方法时,如何只匹配年份和月份?_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 在Rails中,当使用“where”方法时,如何只匹配年份和月份?

Ruby on rails 在Rails中,当使用“where”方法时,如何只匹配年份和月份?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,通常,要选择具有相同日期的所有记录,我们使用如下内容: Bronze.where(regdate: Date.new(2014,03,03)) 如何使用where仅从年和月中进行选择?如果您使用的是mysql,请尝试SQL的提取功能 Bronze.where('extract(year from regdate) = ? AND extract(month from regdate) = ?', year_parameter, month_parameter) 但是如果您使用的是sqlite

通常,要选择具有相同日期的所有记录,我们使用如下内容:

Bronze.where(regdate: Date.new(2014,03,03))

如何使用where仅从年和月中进行选择?

如果您使用的是
mysql
,请尝试SQL的
提取
功能

Bronze.where('extract(year from regdate) = ? AND extract(month from regdate) = ?', year_parameter, month_parameter)
但是如果您使用的是
sqlite
,请尝试以下方法

Bronze.where("strftime('%Y', regdate) = ? AND strftime('%m', regdate) + 0 = ?", year_parameter, month_parameter)
或者干脆

Bronze.where(regdate: Date.new(2014,03,03)).select("YEAR(d) as year, MONTH(d) as month")

其中d是要提取年份和月份的列。

对于月份,它将是:

date = # set your date here
Bronze.where(regdate: date.beginning_of_month...date.beginning_of_month + 1.month)
类似地,一年