【问题标题】:How do I write an ActiveRecord query that filters out results from a joined table?如何编写从联接表中过滤掉结果的 ActiveRecord 查询?
【发布时间】:2016-04-09 11:19:20
【问题描述】:

用户和会话通过has_and_belongs_to_many 关联加入。

如何获取满足以下条件的唯一用户列表?

  • user.coach == true
  • user.available == true

如果该用户是任何活动会话中的教练,则不包括该用户:

  • session.coach_id == user.id
  • session.call_ends_at == nil

有没有办法可以用 ActiveRecord 查询语言编写这个?我需要写一个纯SQL语句吗?某种混合体?你会怎么做?

我还定义了可能对这里有所帮助的范围。但我不确定如何添加它们:

  • User.available_coaches(范围)
  • Session.in_progress(范围)

用户模型

class User < ActiveRecord::Base
  has_many :client_sessions, class_name: 'Session', foreign_key: :client_id
  has_many :coach_sessions, class_name: 'Session', foreign_key: :coach_id

  scope :coaches, -> { where(coach: true) }
  scope :available_coaches, -> { coaches.where(available: true) }

会话模型

class Session < ActiveRecord::Base
  belongs_to :client, class_name: 'User'
  belongs_to :coach, class_name: 'User'

  scope :in_progress, -> { where.not(coach: nil).where(call_ends_at: nil) }

架构

create_table "sessions", force: :cascade do |t|
  t.integer  "client_id"
  t.integer  "coach_id"
  t.boolean  "canceled",          default: false
  t.datetime "coach_accepted_at"
  t.datetime "call_begins_at"
  t.datetime "call_ends_at"
  t.datetime "created_at",                        null: false
  t.datetime "updated_at",                        null: false
end

add_index "sessions", ["client_id"], name: "index_sessions_on_client_id", using: :btree
add_index "sessions", ["coach_id"], name: "index_sessions_on_coach_id", using: :btree

create_table "users", force: :cascade do |t|
  t.string   "first_name"
  t.string   "last_name"
  t.boolean  "coach",             default: false
  t.boolean  "available",         default: false
  t.datetime "created_at",                        null: false
  t.datetime "updated_at",                        null: false
end

【问题讨论】:

  • User.joins(:sessions).where(coach: true, available: true).where.not(sessions: {coach_id: user.id, call_ends_at: nil }) - 检查这是否适合你,我没有测试过。
  • 谢谢!!它非常接近并帮助我解决了它。 User.joins(:coach_sessions).where(coach: true, available: true).where.not(sessions: {call_ends_at: nil }).uniq
  • 嗯...实际上这并没有。我需要找到没有call_ends_at: nil 会话的用户。这将返回具有将任何call_ends_at 设置为非零的会话的用户。这有意义吗?
  • 更新了描述。
  • 所以另一种说法是,我只想看到拥有 0 个会话且拥有 session.call_ends_at == nil 的用户。

标签: sql ruby-on-rails ruby rails-activerecord


【解决方案1】:

我会用 SQL exists:

User.where(coach: true, available: true).
  where("not exists (select 1 from sessions " +
    "where sessions.coach_id = users.id and sessions.call_ends_at is null)")

请注意,由于没有连接到 sessions,因此不需要 .uniq。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多