class User < ActiveRecord::Base
has_many :user_notifications
end
class UserNotification < ActiveRecord::Base
belongs_to :user
end
我正在尝试让所有不的用户拥有任何user_notifications记录。可以使用范围来完成吗?
答案 0 :(得分:1)
我的前面没有任何项目,但是因为我记得,你可以做以下事情:
scope :filtered_users, -> { eager_load(:user_notifications).where(user_notifications.user_id: nil) }
答案 1 :(得分:1)
在where语句中使用SQL:
scope :no_notifications, -> {includes(:user_notifications).where('NOT EXISTS(select * from user_notifications where user_notifications.user_id = users.id)')}
答案 2 :(得分:1)
class User < ActiveRecord::Base
has_many :user_notifications
scope :without_notifications, -> { joins("LEFT OUTER JOIN user_notifications ON users.id = user_notifications.user_id").where(user_notifications.id: nil) }
end
答案 3 :(得分:1)
我喜欢developer033的版本,但我认为您需要使用where
中的哈希语法:
scope :without_notificatons, lambda {
eager_load(:user_notifications).where(user_notifications: { user_id: nil })
}
当你使用Rails 5时,你可以使用left_outer_joins
更具可读性和更具吸引力的内容。
scope :without_notificatons, lambda {
left_outer_joins(:user_notifications).where(user_notifications: { user_id: nil })
}