【问题标题】:Rails where with custom model methodRails where 使用自定义模型方法
【发布时间】:2015-06-30 03:20:15
【问题描述】:

我使用的是 Rails 4,有一个 notifs 和一个 users 模型。

每个notif has_many users(又名user 见过notif)。我正在尝试获取current_user 未看到的所有通知。为了检查current_user 是否看到通知,我正在使用这个模型类:

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

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

类似:

Notif.where(seen_by(current_user): true)

【问题讨论】:

    标签: ruby-on-rails activerecord notifications rails-activerecord where


    【解决方案1】:

    这里基本上需要一个反连接模式,例如可以使用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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多