在我的应用程序中,我的模型定义了和Sinatra
之间的 HABTM 关系。我正在尝试定义几个范围,一个用于所有与 no call 相关联的范围,一个返回所有被特定的“未读”的范围。Users
Notifications
Notifications
Users
unread
Notifications
User
class Notification < ActiveRecord::Base
has_and_belongs_to_many :users
scope :unread, ->{
Notification.joins("LEFT JOIN notifications_users ON notifications.id = notifications_users.notification_id").
where("notifications_users.user_id IS NULL").uniq
}
scope :unread_by, ->(u){
Notification.joins("LEFT JOIN notifications_users ON notifications.id = notifications_users.notification_id").
where("notifications_users.user_id <> ?", u.id).uniq
}
范围工作正常,unread
但unread_by
范围没有给我预期的结果。
it "should know which notifications have not yet been read by anyone, or by a particular user" do
n1 = Notification.create!(title: 'test 1', text: 'this is some longer text about the notification')
n2 = Notification.create!(title: 'test 2', text: 'this is also some longer text about the notification')
Notification.unread.must_include(n1)
Notification.unread.must_include(n2)
@user1.read(n1)
Notification.unread.wont_include(n1)
Notification.unread.must_include(n2)
Notification.unread_by(@user1).wont_include(n1)
Notification.unread_by(@user1).must_include(n2) # => fails
Notification.unread_by(@user2).must_include(n1)
Notification.unread_by(@user2).must_include(n2) # => fails
end
我怀疑我的查询逻辑有缺陷,但我已经盯着这个太久了,我只是没有看到它。我错过了什么?