【问题标题】:Finding an association寻找关联
【发布时间】:2022-06-29 02:21:34
【问题描述】:

我正在尝试查询尚未在关联组中的所有记录。因此,我正在使用四个模型,包括 has_many through 关联:

  • Account 其中has_one :credentialhas_many :user_places
  • Credential 其中belongs_to :account
  • UserPlace 其中belongs_to :accountbelongs_to :place
  • Place 其中has_many :user_placeshas_many :accounts, through: :user_places

我正在尝试查询不在当前位置的Credentials。自从我使用 Rails 以来已经有一段时间了,而且我在没有编写一堆原始 SQL 的情况下就已经掌握了逻辑。

到目前为止,我有类似的东西: Credential.where('name LIKE ?', '%query%').joins(account: :user_place).
如果我用 psudo 代码写出我需要的东西,我认为它会是这样的:

Credential.where('name LIKE ?', '%query%').joins(account: :user_place).where.not(account_id == UserPlace.account_id)

【问题讨论】:

  • 你为什么用 LIKE 进行 where 查询?这里缺少一些信息。
  • 要查找具有匹配搜索查询的name 的用户,我只是不想显示已经在该位置的用户。

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


【解决方案1】:

当你想在 Rails 中查询连接表时,你可以像下面这样尝试。

Credential.where('name LIKE ?', '%query%').joins(account: :user_place).where.not(user_places: {account_id: account_id})

我假设 db 中的 UserPlace 表名是 user_places 否则你需要修改它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多