How to get records created at the current month?

后端 未结 4 751
小蘑菇
小蘑菇 2021-02-15 18:12

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_m         


        
4条回答
  •  醉梦人生
    2021-02-15 18:38

    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) }
    

    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.

提交回复
热议问题