【问题标题】:active record join two tables with where活动记录用 where 连接两个表
【发布时间】:2016-02-02 14:35:24
【问题描述】:

我有模特

class PatientProfile < ActiveRecord::Base
  has_many :friendships

  with_options through: :friendships, source: :friend do |model|
    model.has_many :friends, -> { where(friendships: { status: 'accepted'}) }
    model.has_many :friend_requests, -> { where(friendships: { status: 'requested'}) }
    model.has_many :requested_friendships, -> { where(friendships: { status: 'requestor'}) }
  end

uids = ["123", "456"]

我想查询PatientProfile查找uid在uids数组中的所有记录,并且没有两个用户之间的友谊记录。

这应该可以通过加入来实现,但我在documentation 中被绊倒了

编辑:

uidPatientProfile

Friendships 表中有两列,friend_idpatient_profile_id。我只想要PatientProfile,其中friend 不在uids 列表中,而patient_profile_id 不是,比如说,1

【问题讨论】:

  • ... 和uid 列属于哪个模型?
  • @ArupRakshit PatientProfile
  • 如何生成uid 列表?
  • @МалъСкрылевъ 它来自第三方
  • @user2954587 通过 Rails 应用程序外部的请求?

标签: ruby-on-rails activerecord


【解决方案1】:

我们缺少一些关于你的意思没有友谊记录的上下文,但如果你正在寻找记录,那么与 uid 的友谊为 0:

PatientProfile.includes(:friendships).where(uid: [123, 456], friendships: {id: nil})

更新

或者,如果您更喜欢范围版本:

scope :no_friendships, -> { includes(:friendships).where(friendships: {id: nil}) }

所以现在你可以这样做了:

PatientProfile.no_friendships.where(uid: [123, 456])

【讨论】:

  • 没有两个用户之间的友谊记录 OP 的台词让我很困惑。
  • 我用更多信息更新了问题,希望对您有所帮助,对造成的混乱表示歉意
猜你喜欢
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
相关资源
最近更新 更多