User
モデルとGroup
モデルがあります。 User
belongs_to Group
。 Group
の属性はcheck_minutes
です。Rails:n分前のすべてのユーザーを検索する方法。nは結合グループに格納されます。
ユーザモデルにold
とfresh
という2つのスコープを作成したいとします。古いユーザーはcreated_at
のユーザーがuser.group.check_minutes.ago
より古いユーザーです。新鮮なユーザーはのユーザーがuser.group.check_minutes.ago
より新しい。
私はスコープを書いた:
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)")
そしてスペック:
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
仕様は、(old
のために、それはOKです)fresh
に失敗:間違って何
expected [#<User id: 7967, ... >]
got []
!どのように私のスコープ\ specsをうまく動作させるには?
スコープを整理するには、より良い方法がわかっているといいでしょう。
-rails –
本当にいいです、+1 – apneadiving
ありがとう!できます。記事は非常に便利です! Спасибо:) – petRUShka