Rails 使用自定义模型方法的地方

Rails where with custom model method

我正在使用 Rails 4,并且有一个 notifs 和一个 users 模型。

每个 notif has_many users(也就是 user 看到了 notif)。我正在尝试获取 current_user 未看到的所有通知。为了检查 current_user 是否看到通知,我正在使用此模型 class:

def seen_by?(u)
  return self.users.include?(u)
end

如何使用调用获取 seen_by(current_user)true 的所有通知?

类似于:

Notif.where(seen_by(current_user): true)

基本上你需要一个反连接模式,例如,可以用 left join/is nullnot in/subquerynot exists/subquery 检查来执行。第一个问题是您不能在没有原始 sql(或重写关联)的情况下在 on 子句中指定条件。所以你可以在这里使用 not in 和一个单独的查询方法:

Notif.where.not(id: User.where(id: current_user_id).pluck[:notif_id])