How to get records created at the current month?

后端 未结 4 752
小蘑菇
小蘑菇 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:28

    You could use an ActiveRecord Association Extension:

    #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
    

    This should allow you to call @candidate.votes.from_this_month to return the required conditional data

提交回复
热议问题