如何获取当月创建的记录? [英] How to get records created at the current month?

查看:59
本文介绍了如何获取当月创建的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个候选人有很多票。

I have a candidate which has_many votes.

我要获取当月创建的候选人的票吗?

I am trying to get the votes of a candidate that were created in the current month?

@candidate.votes.from_this_month

scope :from_this_month, where("created_at > ? AND created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)

这给了我一个PG错误:
PG ::错误:错误:列引用\ created_at\不明确

That gives me a PG error: PG::Error: ERROR: column reference \"created_at\" is ambiguous

如果我尝试

scope :from_this_month, where("vote.created_at > ? AND vote.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)

我遇到以下错误

PG::Error: ERROR:  missing FROM-clause entry for table "vote"


推荐答案

您还需要在lamda中加上位置。

You need to enclose the where in a lamda as well.

scope :from_this_month, lambda { where("votes.created_at > ? AND votes.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month) }

否则,它似乎可以正常工作,您的测试将全部通过,但是如果您的应用运行了一个多月,您将开始获得不正确的结果,因为Time.now在类加载时而不是在调用方法时进行评估。

Otherwise it may appear to work and your tests will all pass, but if your app runs for more than a month you will start to get incorrect results because Time.now is evaluated when the class loads, not when the method is called.

这篇关于如何获取当月创建的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆