ruby on rails - Dynamically get records between two dates -


i'm working on project @ moment have voting system , on index page vote model can see average vote last week. i'd able have user able choose date between rating averaged. i'm not sure how go doing this.

currently have view shows @average defined as:

vote.where(date: (date.today - 7)..(date.today)).average(:score) 

my initial though include 'date range' attribute model , have average calculated dates, set form in index view, seems lot of overhead such simple task.

any appreciated.

as wanted achieve model point of view, can use dynamic scope of rails achieve this,

in model,

method1:

class vote < activerecord::base    scope :average_score, ->(date1,date2) { where(date: (date1)..(date2) )}   end 

now, on controller or view , can call like,

@average = vote.average_score(date.today - 7 , date.today).average(:id)

method 2:

you can take method , call scope method.

class vote < activerecord::base        scope :average_score, ->(date1,date2) { where(date: (date1)..(date2) )}           def self.average_score_value(d1, d2)         self.average_score(d1,d2).average(:id)        end  end 

now, on controller or view , can call like,

@average = vote.average_score_value(date.today - 7 , date.today)

here example user table, have taken created_at column

2.3.1 :036 > user.average_score(date.today - 7,date.today).average(:id)   (0.5ms)  select avg(`users`.`id`) `users` (`users`.`created_at` between '2016-10-19' , '2016-10-26')  => nil  

the scope is,

scope :average_score, ->(date1,date2) { where(created_at: (date1)..(date2) )}

here reference


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -