gra*_*ury 7 ruby postgresql ruby-on-rails
我有一个有很多选票的候选人.
我想获得本月创建的候选人的投票?
@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)
Run Code Online (Sandbox Code Playgroud)
这给了我一个PG错误:PG ::错误:错误:列引用\"created_at \"是不明确的
如果我试试
scope :from_this_month, where("vote.created_at > ? AND vote.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
PG::Error: ERROR: missing FROM-clause entry for table "vote"
Run Code Online (Sandbox Code Playgroud)
Har*_*dik 10
正确的范围
scope :from_this_month, lambda {where("votes.created_at > ? AND votes.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)}
Run Code Online (Sandbox Code Playgroud)
这是因为在轨道中,模型名称是单数(即Vote),并且创建的表格是votes通过对流的pural(例如)
编辑
这可以写得更简单,lambda {where(created_at: Time.now.beginning_of_month..(Time.now.end_of_month))}我们需要使用lambda,因为下面的注释给出了原因.
Thanx BroiSatse提醒:D
你需要将lamda中的where括起来.
scope :from_this_month, lambda { where("votes.created_at > ? AND votes.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month) }
Run Code Online (Sandbox Code Playgroud)
否则它似乎可以工作,你的测试将全部通过,但是如果你的应用程序运行超过一个月,你将开始得到不正确的结果,因为在类加载时评估Time.now,而不是在调用方法时.
从 Rails 5 开始,您将拥有更加简洁的语法。在您的投票模型上添加范围this_month
scope :this_month, -> { where(created_at: Date.today.all_month) }
Run Code Online (Sandbox Code Playgroud)
您现在可以查询@candidates.votes.this_month