Reputation: 2430
I have the following SQL query which I use to fetch some rows from a mySQL database :
SELECT code_ver, result FROM mastertest WHERE date >= DATE_SUB( (CURDATE()) , INTERVAL 90 DAY) ORDER BY date DESC;
This query gives me data from the past 90 days. Now I want to display the data of 10 days at a time in my html.erb page (view). I am aware that pagination can be done using 'will_paginate' and 'kaminari' gems. But I am not sure how to query the database with certain conditions as shown above.
Can someone help me with the code here?
Upvotes: 0
Views: 650
Reputation: 11904
This is how you could construct that in ActiveRecord:
Mastertest.where('date >= ?', Time.now - 90.days ).order('date DESC').select("code_ver, result")
From here, you can either chain will_paginate or kaminari methods, or roll your own if you want. You may want to roll that query into a class method if you will be using it a lot:
class Mastertest
def self.last_90_days
where('date >= ?', Time.now - 90.days ).order('date DESC').select("code_ver, result")
end
## here's a simple pagination example:
def self.page(page,per_page)
limit(per_page).offset((page - 1) * per_page)
end
end
Mastertest.last_90_days.page(1,20) #=> [...]
Upvotes: 1