I have User model and Group model. User belongs_to Group. Group has an attribute check_minutes.
I want to create two scopes in User model: old and fresh. Old users is users with created_at older than user.group.check_minutes.ago. And fresh users is users with created_at newer than user.group.check_minutes.ago.
I wrote the scopes:
scope :old, joins(:group).where("`users`.`created_at` <=
DATE_SUB(NOW(), INTERVAL `groups`.`check_minutes` MINUTE)")
scope :fresh, joins(:group).where("`users`.`created_at` >
DATE_SUB(NOW(), INTERVAL `groups`.`check_minutes` MINUTE)")
And specs:
describe "scopes" do
let(:group) {Group.make :check_minutes => 20}
let(:old_user) {User.make :group => group, :created_at => 30.minutes.ago}
let(:new_user) {User.make :group => group, :created_at => 10.minutes.ago}
context "#fresh" do
it "should scope all new users" do
User.fresh.should eq([ new_user ])
end
end
context "#old" do
it "should scope all old users" do
User.old.should eq([ old_user ])
end
end
end
Specs fails on fresh (for old it is ok):
expected [#<User id: 7967, ... >]
got []
What’s wrong?! How to force my scopes\specs to work well?
It would be great If you know the better way to organize scopes!
Your scopes are OK.
The problem you’re having is that Rails stores UTC time values in the database, regardlessly of the database’s configured time zone, and converts them into your (Rails) timezone while doing ORM.
…Which means your scopes are almost OK – you just have to inject the ‘Rails’ current time into the query.