How to get records created in the current month?

I have a candidate who has_many votes.

Am I trying to get the votes of a candidate created this 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)

This gives me the error PG: PG :: Error: ERROR: the column reference \ "created_at \" is ambiguous

If i try

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

I get the following error

PG::Error: ERROR:  missing FROM-clause entry for table "vote"
+4
source share
3 answers

You also need to attach a spot in the lamp.

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

Otherwise, it may work and your tests will pass, but if your application has been running for more than a month, you will start to get incorrect results, because Time.now is evaluated when the class is loaded, and not when the method is called.

+5
source

The correct scope

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

, (i.e Vote), pural (, votes)

lambda {where(created_at: Time.now.beginning_of_month..(Time.now.end_of_month))}, , .

Thanx BroiSatse : D

+8

ActiveRecord Association:

#app/models/Candidate.rb
Class Candidate < ActiveRecord::Base
   has_many :votes do
       def from_this_month
           where("created_at > ? AND created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)
       end
   end
end

@candidate.votes.from_this_month,

0

Source: https://habr.com/ru/post/1531907/


All Articles